Maximum Depth of Binary Tree

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.

一样的。

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int maxDepth(TreeNode root) {
12         // IMPORTANT: Please reset any member data you declared, as
13         // the same Solution instance will be reused for each test case.
14         ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
15         int result = 0;
16         if(root == null) return result;
17         queue.add(root);
18         TreeNode nl = new TreeNode(Integer.MIN_VALUE);
19         queue.add(nl);
20         while(queue.size() != 1){
21             TreeNode rn = queue.remove(0);
22             if(rn.val == Integer.MIN_VALUE){
23                 queue.add(nl);
24                 result ++;
25             }
26             else{
27                 if(rn.left != null) queue.add(rn.left);
28                 if(rn.right != null) queue.add(rn.right);
29             }
30         }
31         return ++result;
32     }
33 }

 

posted on 2013-11-16 05:54  Step-BY-Step  阅读(130)  评论(0编辑  收藏  举报

导航