算法day12 | Java | 二叉树 | LeetCode 翻转、对称二叉树;最大深度最小深度

58 阅读2分钟

java

二叉树

二叉树的深度depth:某个节点到根节点的距离(从1开始)。

二叉树的高度:某个节点到叶子节点的距离。(叶子结点的告诉是1)

求高度使用后续遍历,求深度用前序遍历。

根节点的高度就是二叉树的最大深度。

226.翻转二叉树

递归

选择什么遍历方式:前序/后序。

为什么不能用中序?先处理左子树->根->右子树,代码逻辑应该先处理左子树,再处理根节点,再处理左子树

遍历结束条件:cur == null

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

    private void preOrder(TreeNode t) {
        if(t == null) return;
        TreeNode node = t.left;
        t.left = t.right;
        t.right = node;

        preOrder(t.left);
        preOrder(t.right);
    }
}

101. 对称二叉树

思路:同时遍历左右子树。?思路错了…

正确思路:确定遍历顺序,只能是后序。因为我们要不断收集左右孩子的信息返回给上一个节点。什么情况需要使用后序呢?当我们需要收集完左右子树的信息返回给上一层时。

class Solution {
    public boolean isSymmetric(TreeNode root) {
       if(root == null) return true;
       return preOrder(root.left, root.right);
    }

    //只要有一点不同,那么就是false
    private boolean preOrder(TreeNode left, TreeNode right) {
        if(left == null && right == null) return true;
        if(left == null && right != null || left != null && right == null) return false;
        if(left.val != right.val) return false;
        return preOrder(left.left,right.right) && preOrder(left.right, right.left);
    }

}

104.二叉树的最大深度

我的解法:层序遍历

class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null) return 0;

        Queue<TreeNode>q = new LinkedList<>();
        q.offer(root);
        int height=0;
        while(!q.isEmpty()) {
            height++;
            int size = q.size();
            for(int i=1; i<=size; i++) {
                TreeNode node = q.poll();
                if(node.left!=null) q.offer(node.left);
                if(node.right!=null) q.offer(node.right);
            }   
        }

        return height;
    }
}

需要掌握一下递归法:

二叉树的最大深度是 左子树或者右子树里最大深度+1

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

111.二叉树的最小深度

题目中给的最小深度的定义是根节点到叶子节点的最小距离,和本来的定义不一样。

正确解法:

这道题和最大深度不太一样,一定要注意。

class Solution {
    public int minDepth(TreeNode root) {
        //其实这道题求的是叶子节点的最小高度
        if(root == null) return 0;

        int leftH = minDepth(root.left);
        int rightH = minDepth(root.right);

        if(root.left == null) {
            return rightH+1;
        }

        if(root.right == null) {
            return leftH+1;
        }

        // 左右结点都不为null
        return Math.min(leftH, rightH) + 1;
    }
}