Sunday, May 11, 2014

Leetcode: 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.

Solution:



Recursive:

/**
 * 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;
        return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
    }
}


Iterative:

/**
 * 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 max=0;
        Deque<TreeNode> nodeStack = new ArrayDeque<TreeNode>();
        Deque<Integer> depthStack = new ArrayDeque<Integer>();
        nodeStack.addFirst(root);
        depthStack.addFirst(1);
        while(!nodeStack.isEmpty())
        {
            TreeNode node = nodeStack.removeFirst();
            int depth = depthStack.removeFirst();
            max = depth>max ? depth : max;
            if (node.left != null)
            {
                nodeStack.addFirst(node.left);
                depthStack.addFirst(depth+1);
            }
            if(node.right != null)
            {
                nodeStack.addFirst(node.right);
                depthStack.addFirst(depth+1);
            }
        }
        return max;
    }
}

No comments :

Post a Comment