码迷,mamicode.com
首页 > 其他好文 > 详细

Maximum Depth of Binary Tree

时间:2017-09-03 10:08:39      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:tree   down   queue   empty   bin   ges   path   com   its   

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.

 

分析:用层次遍历,记录下访问深度即可。参考 http://www.cnblogs.com/baichangfu/p/7461433.html

JAVA CODE

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        int deep = 0;
        Queue<TreeNode> queue = new ArrayDeque<>();
        Queue<Integer> queue1 = new ArrayDeque<>();
        if(root!=null){
            queue.offer(root);
            queue1.offer(new Integer(deep++));
        }
        while(!queue.isEmpty()){
            root = queue.poll();
            int hh = queue1.poll().intValue();
            if(deep == hh){
                deep++;
            }
            if(root.left!=null){
                queue.offer(root.left);
                queue1.offer(new Integer(deep));
            }
            if(root.right!=null){
                queue.offer(root.right);
                queue1.offer(new Integer(deep));
            }
        }
        return deep;
    }
}

 

Maximum Depth of Binary Tree

标签:tree   down   queue   empty   bin   ges   path   com   its   

原文地址:http://www.cnblogs.com/baichangfu/p/7468706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!