Maximum Depth of Binary Tree 二叉树的最大深度

本文介绍了一种求解二叉树最大深度的有效算法。利用队列实现层次遍历,并结合递归方法,实现了简洁高效的代码。适用于计算机科学与技术领域的初学者及进阶者。

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.


因为有前边的一些练习,这道题目做起来简直是太简单。

主要思路:用一个Queue记录各个节点,设置一个当前层节点的监测数和下层节点的监测数,当添加子节点的时候下层节点的监测数加1,当弹出一个节点的时候,当前层节点的监测数减1,在当前层节点的监测数为0且下层节点的监测数为0的时候,返回深度,否则,把下层节点数赋值给当层节点数作为新的当层节点数,下层节点数置为0,重新开始下一轮计数。

public class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)  return 0;
        Queue<TreeNode> Node=new LinkedList<TreeNode>(); //写成了Queue而不是LinkedList,显得高大上一些。
        Node.add(root);
        int curcount=1;
        int nexcount=0;
        int maxdepth=0;
        while(!Node.isEmpty()){
            TreeNode node=Node.poll();
            --curcount;
            if(node.left!=null){
                Node.add(node.left);
                ++nexcount;
            }
            if(node.right!=null){
                Node.add(node.right);
                ++nexcount;
            }
            if(curcount==0){
                if(nexcount==0)   return ++maxdepth; //只有这种情况下边才返回
                curcount=nexcount;
                nexcount=0;
                ++maxdepth;
            }
        }
        return maxdepth;
    }
}

在粘贴上边部分代码的时候,突然意识到当满足备注那一句的时候,恰好是while语句退出的条件啊,相辅相成。故而删除那一句(从逻辑上来说是多余的),直接通过

public class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)  return 0;
        Queue<TreeNode> Node=new LinkedList<TreeNode>();
        Node.add(root);
        int curcount=1;
        int nexcount=0;
        int maxdepth=0;
        while(!Node.isEmpty()){
            TreeNode node=Node.poll();
            --curcount;
            if(node.left!=null){
                Node.add(node.left);
                ++nexcount;
            }
            if(node.right!=null){
                Node.add(node.right);
                ++nexcount;
            }
            if(curcount==0){
                curcount=nexcount;
                nexcount=0;
                ++maxdepth;
            }
        }
        return maxdepth;
    }
}

下边是我尝试性的写了一下递归,竟然一次性通过,太开心了。第一次递归通过,一直不会用递归啊。

递归其实只有一个要求,先确定问题能用递归解决,然后只需要拿出第一层的那个问题,把它写出来了,整个递归就出来了

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

但是依旧可以把递归简化为下边这样

public class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)  return 0;
        return Math.max(maxDepth(root.left),maxDepth(root.right))+1; //这一句便覆盖了所有的情况
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值