2014年5月9日星期五

Recursive/Loop Binary Tree Solution - Maximum Depth of Binary Tree

The idea is to either recursive call children, or use a queue to process nodes, count the height at the same time. Both work.


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        // int leftDepth = maxDepth(root.left);
        // int rightDepth = maxDepth(root.right);
        // return leftDepth > rightDepth?leftDepth + 1 : rightDepth + 1;
        Queue<TreeNode> process = new LinkedList<TreeNode>();
        process.offer(root);
        int count = process.size();
        int height = 0;
        while(!process.isEmpty()){
            TreeNode temp = process.poll();
            count--;
            if(temp.left != null){
                process.offer(temp.left);
            }
            if(temp.right != null){
                process.offer(temp.right);
            }
            if(count == 0){
                count = process.size();
                height++;
            }
        }
        return height;
    }
}

没有评论: