代码随想录二刷第二十天 | 226.翻转二叉树、101. 对称二叉树、104.二叉树的最大深度、111.二叉树的最小深度

36 阅读2分钟

226.翻转二叉树

题目:226. 翻转二叉树 - 力扣(LeetCode)

题解:代码随想录

状态:AC

思路

将每个节点的左右子节点进行交换即可,使用前后序递归都能快速解决

代码

时间复杂度:O(N) 空间复杂度:O(H)

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return root;
        invert(root);
        return root;
    }

    private void invert(TreeNode node){
        if(node == null) return;
        TreeNode temp = node.left;
        node.left = node.right;
        node.right = temp;
        invert(node.left);
        invert(node.right);
    }
}

101. 对称二叉树

题目:101. 对称二叉树 - 力扣(LeetCode)

题解:代码随想录

状态:需要多复习

思路

要遍历两棵树,且要比较内侧和外侧节点,所以一个树的遍历顺序是左右中,一个树的遍历顺序是右左中。

代码

时间复杂度:O(N) 空间复杂度:O(H)

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return compare(root.left, root.right);
    }

    private boolean compare(TreeNode left, TreeNode right){
        if(left == null && right == null) return true;
        if(left == null || right == null || left.val != right.val) return false;

        return compare(left.left, right.right) && compare(left.right, right.left);
    }
}

104.二叉树的最大深度

题目:104. 二叉树的最大深度 - 力扣(LeetCode)

题解:代码随想录

状态:AC

思路

分别递归左右子树,取最大值

代码

时间复杂度:O(N) 空间复杂度:O(N)

class Solution { public int maxDepth(TreeNode root) { if (root == null) return 0; return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); } }

111.二叉树的最小深度

题目:111. 二叉树的最小深度 - 力扣(LeetCode)

题解:代码随想录

状态:需要和最大深度区分

思路

这里要注意下最小深度的含义:从根节点到最近叶子节点的最短路径上的节点数量

代码

时间复杂度:O(N) 空间复杂度:O(N)

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right != null) return minDepth(root.right) + 1;
        if (root.right == null && root.left != null) return minDepth(root.left) + 1;

        return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
    }
}