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

二叉树的最大深度

http://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73

  • 解法1:递归dfs
  • 解法2:队列bfs层序遍历

解法1:递归


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
        if(root == null) {
            return 0;
        }
        int res = dfs(root,0);
        return res;
        
    }
    //递归dfs遍历
    public int dfs(TreeNode root, int depth){
        if(root == null) {
            return depth;
        }
        if(root.left == null && root.right == null){
            return depth+1;
        }
        return Math.max(dfs(root.left,depth+1),dfs(root.right,depth+1));
    }
}

解法2:队列bfs层序遍历

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        if(root == null) {
            return 0;
        }
        int res = bfs(root);
        return res;
        
    }
 	//队列层序遍历
    public int bfs(TreeNode root){
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int res = 0;
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0; i < size; i++){
                TreeNode node = queue.poll();
                //list放入null会占用一个空间,
                //list加入null判断isEmpty结果是否,size同样会加1
                if(node.left != null){
                    queue.add(node.left);
                }
                if(node.right != null){
                    queue.add(node.right);
                }
            }
            res++;
        }
        return res;
    }
}
全部评论

相关推荐

都是平常模拟联系了,开个摄像头,还要不要隐私了。。。
SalaryWish...:可能想还原真实面试场景吧,而且一些企业的AI面都是牛客做的,我觉得底层是一样的
点赞 评论 收藏
分享
只对一道题还有机会吗
投递OPPO等公司10个岗位
点赞 评论 收藏
分享
码农索隆:想看offer细节
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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