首页 > 其他 > 详细

Maximum Depth of Binary Tree

时间:2017-03-12 10:43:59      阅读:153      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

Maximum Depth of Binary Tree

原文:http://www.cnblogs.com/codingEskimo/p/6536880.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!