Bootstrap

代码随想录算法训练营第十四天|二叉树 part2

226. 翻转二叉树

递归地将左右节点互换,前序遍历。

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == nullptr)
            return root;
        swap(root->left, root->right);
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

101. 对称二叉树

同步后序遍历两个二叉树,当两者不相同(包括空)时返回false,当两者都空时返回true。当数值相同,继续比较,分内外侧。

class Solution {
public:
    bool compare(TreeNode* left, TreeNode* right) {
        if (left == nullptr && right != nullptr)
            return false;
        else if (left != nullptr && right == nullptr)
            return false;
        else if (left == nullptr && right == nullptr)
            return true;
        else if (left->val != right->val)
            return false;
        
        bool outside = compare(left->left, right->right);
        bool inside = compare(left->right, right->left);
        return outside && inside;
    }
    bool isSymmetric(TreeNode* root) {
        if (root)
            return compare(root->left, root->right);
        else 
            return true;
    }
};

104. 二叉树的最大深度

通过后序遍历,求得左右子树的最大高度,最终得到二叉树的最大高度,也是最大深度。

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

111. 二叉树的最小深度

整体思路和上面一样,把最大换成最小,但是要注意最小深度是到最近的叶子节点,也就是说要跳过只有一个子树的节点,这是陷阱。

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (root == nullptr)
            return 0;
        
        int left = minDepth(root->left);
        int right = minDepth(root->right);
        if (left == 0 && right != 0)
            return 1 + right;
        else if (left != 0 && right == 0)
            return 1+ left;
        else
            return 1 + min(left, right);
    }
};
;