标签: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; } }
标签:tree down queue empty bin ges path com its
原文地址:http://www.cnblogs.com/baichangfu/p/7468706.html