[LeetCode] 104. Maximum Depth of Binary Tree

Good reference for all tree problem  https://sites.google.com/site/jennyshelloworld/company-blog/chapter-3---binary-tree-divide-conquer

Analysis: 

Here we use divide and conquer.

How to divide? We can translate the problem into calculate the maximum depth of left subtrees and right subtrees, let's say leftMax and rightMax

How to conquer? We can find the result is just the maximum of the leftMax and rightMax, do not forget to add 1, which is the distance to the root

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public int maxDepth(TreeNode root) {
        // write your code here
        if (root == null) {
            return 0;
        }
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return Math.max(left, right) + 1;
    }
}

 

posted on 2017-03-12 02:48  codingEskimo  阅读(101)  评论(0编辑  收藏  举报

导航