【代码随想录Day16】二叉树

104 二叉树的最大深度

https://leetcode.cn/problems/maximum-depth-of-binary-tree/

可以BFS记录一个depth每层++,这里用DFS后序遍历, 用DFS前中后序遍历也可以,但需要往下传入一个全局变量depth.

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

111 二叉树的最小深度

https://leetcode.cn/problems/minimum-depth-of-binary-tree/description/

BFS做法,遇到第一个叶子返回depth.

class Solution {      
    public int minDepth(TreeNode root) {
        Queue<TreeNode> queue = new ArrayDeque<>();
        int depth = 0;
        if (root != null) queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            depth++;
            while (size-- > 0) {
                TreeNode cur = queue.poll();
                if (cur.left == null && cur.right == null) return depth;
                if (cur.left != null) queue.offer(cur.left);
                if (cur.right != null) queue.offer(cur.right);
            }
        }
        return depth;
    }
}

DFS 不能直接写

{ if (root == null) return 0;

return Math.min(minLeft, minRight) + 1; }

同时为null时0都有效,其他时候为0时无效忽略改为MAX。

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        int minLeft = minDepth(root.left);
        int minRight = minDepth(root.right);
        if (minLeft == 0 && minRight != 0) minLeft = Integer.MAX_VALUE; 
        if (minRight == 0 && minLeft != 0) minRight = Integer.MAX_VALUE;
        return Math.min(minLeft, minRight) + 1;
    }
}

222完全二叉树的节点个数

https://leetcode.cn/problems/count-complete-tree-nodes/

如果安照普通数的做法,DFS,BFS都可以做时间是O(n),如果考虑到保证是complete tree,那么左右可以不停分解成更小的complete tree直到右子树分解为complete tree. 每个complete tree的节点数为2^height - 1. 注意如果需要递归到下一层,参数是root.left/root.right而不是已经走到null的用来数左右高度的leftRoot, rightRoot.

class Solution {  //每次递归里要while height次,总共递归height层,TO(logn * logn)
    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        int leftDeepth = 0, rightDepth = 0;
        TreeNode leftRoot = root.left, rightRoot = root.right;
        while (leftRoot != null) {
            leftDeepth++;
            leftRoot = leftRoot.left;
        }
        while (rightRoot != null) {
            rightDepth++;
            rightRoot = rightRoot.right;
        }
        if (leftDeepth ==  rightDepth) return (2 << leftDeepth) - 1;
        return countNodes(root.left) + countNodes(root.right) + 1;   //bug countNodes(leftRoot) + countNodes(rightRoot) + 1;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值