Day16代码随想录(1刷) 二叉树

104. 二叉树的最大深度

状态:完成

思路:使用前序遍历的方式求得二叉树的最大深度,每次递归比较左右节点哪个更加大再加上当前节点(+1),最后得到二叉树最大深度。用层序遍历昨天已经实现过了。

class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null) return 0;
        
        return dfs(root);
    }
    public int dfs(TreeNode root){
        if(root==null){
            return 0;
        }
        int left = dfs(root.left);
        int right= dfs(root.right);
        return left>right?left+1:right+1; 
    }
}

 559. N 叉树的最大深度

状态:完成

思路:把上一题对比左右节点的过程换成在children里找最大的过程。

class Solution {
    public int maxDepth(Node root) {
        if(root==null) return 0;
        List<Node> list = root.children;
        int max=0;
        for(Node node:list){
            int temp=maxDepth(node);
            max=max>temp?max:temp;
        }
        return max+1;
    }
}

 111. 二叉树的最小深度

状态:完成

思路:用层序遍历当遍历到左右节点都是空的时候到达底部。也可以用前序遍历和后序遍历去做。

class Solution {
    public int minDepth(TreeNode root) {
        if(root==null) return 0;
        Queue<TreeNode> queue=new LinkedList<>();
        queue.add(root);
        int index=0;
        while(queue.size()>0){
            int size=queue.size();
            for(int i=0;i<size;i++){
                TreeNode node= queue.poll();
                if(node.left!=null) queue.add(node.left);
                if(node.right!=null) queue.add(node.right);
                if(node.left==null&&node.right==null){
                    return index+1;
                }
            }
            index++;
        }
        return index;
    }
}

 前序遍历做法,这里要注意跟最大深度不同的就是当左右节点中有一个节点是null时不能取这个节点的深度要去另一个节点的深度,因为等于null是不存在的,没有深度等于0的二叉树。

class Solution {
    public int minDepth(TreeNode root) {
        if(root==null) return 0;
        int left =minDepth(root.left);
        int right =minDepth(root.right);
        System.out.println(Math.min(left,right));
        return left!=0&&right!=0?Math.min(left,right)+1:Math.max(left,right)+1;
    }
}

222. 完全二叉树的节点个数

状态:一一个个遍历的方式可以做但是下面这种利用完全二叉树性质的方式没有想出来

思路:完全二叉树可以拆成一个个完全二叉树的集合,如果左右节点遍历之后不相等说明这个子树不是完全二叉树,所以遍历这个节点的左右子树直到得到完全二叉树子树为止,相加得到最后结果。

class Solution {
    public int countNodes(TreeNode root) {
        if(root==null) return 0;
        TreeNode node = root;
        int left=0;
        int right=0;
        while(node!=null){
            node=node.left;
            left++;
        }
        node=root;
        while(node!=null){
            node=node.right;
            left++;
        }
        if(left==right){
            return (2<<left)-1;
        }
        return countNodes(root.left)+countNodes(root.right)+1;
    }   
}

  • 16
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值