搜索此博客

2012年10月5日星期五

Depth of Binary Tree

Given a binary tree, find its depth (maximum height).

There are several methods to solve this problem.
The recursion way is straightforward. How about iterative ways?
We first use an in-order traversal method.


01 public int maxHeight(TreeNode root) {
02    if(root==null)
03        return 0;
04    Stack<TreeNode>trees=new Stack<TreeNode>();
05    Stack<Integer>depth=new Stack<Integer>();
06    trees.push(root);
07    int curr_depth=1;
08    depth.push(curr_depth);
09    int maxDepth=1;
10    TreeNode leftNode=root.left;
11    while(leftNode!=null)
12    {
13      
14        trees.push(leftNode);
15        leftNode=leftNode.left;
16        curr_depth++;
17        depth.push(curr_depth);
18      
19    }
20    while(!trees.isEmpty())
21    {
22        TreeNode top=trees.pop();
23        curr_depth=depth.pop();
24        if(curr_depth>maxDepth)
25        {
26            maxDepth=curr_depth;
27        }
28        TreeNode rightNode=top.right;
29        curr_depth++;
30        if(rightNode!=null)
31        {
32            trees.push(rightNode);                              
33            depth.push(curr_depth);
34            TreeNode leftmost=rightNode.left;
35            while(leftmost!=null)
36            {
37                trees.push(leftmost);
38                leftmost=leftmost.left;
39                curr_depth++;
40                depth.push(curr_depth);
41            }
42        }
43    }
44    return maxDepth;
45 }


We can also use a recursion way to solve it.


01 public class Solution {
02     public int maxHeight(TreeNode root) {
03         if(root==null)
04             return 0;
05         else
06         {
07             return findMax(maxHeight(root.left),maxHeight(root.right))+1;
08         }
09       
10     }
11   
12     public int findMax(int a, int b)
13     {
14         return a>b?a:b;
15     }
16 }

没有评论:

发表评论