算法记录Day 16 | 二叉树part03

67 阅读1分钟

算法记录Day 16 | 二叉树part03

LeetCode 104.二叉树的最大深度

题目链接:leetcode.cn/problems/ma…

题解
class Solution {
   public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) {
            return 0;
        }
        return max104(maxDepth(root->left), maxDepth(root->right)) + 1;
    }

    int max104(int a, int b) {
        if (a > b) {
            return a;
        }
        return b;
    }
};

LeetCode 111.二叉树的最小深度

题目链接:leetcode.cn/problems/mi…

题解
class Solution {
   public:
    int minDepth(TreeNode* root) {
        // 结点为空直接返回0
        if (root == nullptr) {
            return 0;
        }
        // 左右结点为空,说明到达叶子结点,返回1
        if (root->left == nullptr && root->right == nullptr) {
            return 1;
        }
        int left = minDepth(root->left);
        int right = minDepth(root->right);
        // 其中一个结点为空(返回0),则返回不为空的结点的深度
        if (root->left == nullptr || root->right == nullptr) {
            return left + right + 1;
        }
        // 当左右都不为空,返回较小深度值+1
        return min111(left, right) + 1;
    }

    int min111(int a, int b) {
        if (a < b) {
            return a;
        }
        return b;
    }
};

LeetCode 222.完全二叉树的节点个数

题目链接:leetcode.cn/problems/co…

题解
class Solution {
   public:
    int count = 0;
    int countNodes(TreeNode* root) {
        if (root == nullptr) {
            return 0;
        }
        helper(root);
        return count;
    }
    void helper(TreeNode* node) {
        if (node == nullptr) {
            return;
        }
        count++;
        helper(node->left);
        helper(node->right);
        return;
    }
};