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

二叉树的最大深度

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

DFS 和 BFS都可以

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;
        }
        Stack<TreeNode> s = new Stack<>();
        Stack<Integer> level = new Stack<>();
        s.push(root);
        level.push(1);
        int max = 0;
        while(!s.isEmpty()){
            TreeNode t = s.pop();
            int flag = level.pop();
            max = Math.max(max,flag);
            if(t.left != null){
                s.push(t.left);
                level.push(flag+1);
            }
            if(t.right != null){
                s.push(t.right);
                level.push(flag+1);
            }       
        }
        return max;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
简历当中有水分算不算造假...
点赞 评论 收藏
分享
深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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