题解 | #二叉树的最大深度#TOP28

思路:
1.递归 Math.max(getMaxHeight(root.left) + 1, getMaxHeight(root.right)+1)
2.记得之前的TOP26层序遍历吗?有多少层深度就是多少,所以直接采用队列,看有多少层就ok了

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        
        //return getMaxHeight(root);
        return maxHeightDFS(root);
    }
    private int getMaxHeight(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = getMaxHeight(root.left) + 1;
        int right = getMaxHeight(root.right) + 1;
        return Math.max(left, right);
    }
    private int maxHeightDFS(TreeNode root){
        if(root == null){
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        int res = 0;
        queue.add(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            while(size -- > 0){
                TreeNode node = queue.poll();
                if(node.left != null){
                    queue.add(node.left);
                }
                if(node.right != null){
                    queue.add(node.right);
                }
            }
            res ++ ;
        }
        return res;
    }
}
面试必刷TOP101 文章被收录于专栏

面试必刷TOP101

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 14:00
林子大了什么鸟都有啊,我觉得我说的已经很客气了,阴阳谁呢
牛客62656195...:应该不是阴阳吧?你第一次注册的时候boss就说你是牛人
点赞 评论 收藏
分享
lllllkin:感觉可以精简到一页简历,有些排版感觉不是必须的。 时间线越早的,你自己越熟悉的放前面。描述可以更精简些,一些问题解决感觉可以不用写具体技术栈,卖个关子,等面试官问。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 17:10
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务