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

226.翻转二叉树

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

很重要的一点:翻转二叉树,实质就是把每个节点的左右孩子都交换一遍。

递归要简单很多,因为要处理的和要遍历的节点是一致的,所以直接遍历就好,不用考虑额外的事情。

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

    public 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)

难度写的是easy,我怎么觉得这道题一点都不简单。。。

首先这道题并不是常规的二叉树遍历,要分成左右两棵子树来做。还是思考递归的三要素

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        return compare(root.left, root.right) ;
    }
    public boolean compare (TreeNode left, TreeNode right) {
        if (left == null && right == null) return true;
        if (left == null || right == null) return false;
        return left.val == right.val && compare(left.left, right.right) && compare(left.right, right.left);
    }
}

104. 二叉树的最大深度

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

首先要想明白二叉树的遍历顺序,采用后续遍历,因为要在遍历了左右子树后,比较深度。

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. 二叉树的最小深度

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

这道题有迭代的思路,用层序遍历,遇到左右孩子都为空的节点,直接返回深度,不用再往下遍历了。

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        int depth = 0;
        while (!deque.isEmpty()) {
            int size = deque.size();
            depth++;
            for (int i = 0; i < size; i++) {
                TreeNode poll = deque.poll();
                if (poll.left == null && poll.right == null) {
                    return depth;
                }
                if (poll.left != null) {
                    deque.offer(poll.left);
                }
                if (poll.right != null) {
                    deque.offer(poll.right);
                }
            }
        }
        return depth;
    }
}

day14完结撒花~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值