Search This Blog

Sunday, December 16, 2012

LeetCode:Maximum Depth of Binary Tree

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.
» Solve this problem

public class Solution {
    public int maxDepth(TreeNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<TreeNode> prev = new ArrayList<TreeNode>();
        
        if(root!=null) prev.add(root);
        int depth=0;
        while(!prev.isEmpty()){
            ArrayList<TreeNode> temp = new ArrayList<TreeNode> ();
            for(TreeNode node:prev){
                if(node.left!=null) temp.add(node.left);
                if(node.right!=null) temp.add(node.right);
            }    
            prev = new ArrayList<TreeNode>(temp);
            depth++;
        }
        return depth;
    }
}

1 comment:

Anonymous said...

Brilliant!