首页 > 其他 > 详细

[lintcode]Maximum Depth of Binary Tree

时间:2015-10-06 12:50:15      阅读:219      评论:0      收藏:0      [点我收藏+]

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.

Example

Given a binary tree as follow:

  1
 / \ 
2   3
   /   4   5

The maximum depth is 3.

SOLUTION:

这题就可以用到二叉树万能大法-Divide & Conquer,分治法!

思路就是,从局部去考虑,一棵树的最大高度就是左子树最大高度与右子树最大高度的最大值(Math.max(left, right)) 加上本身root占的一个高度(+1)

也就是,左边递归一次求最大值,右边递归求最大值,这两个中最大的值再加 1 ,递归到底的时候就会返回,每次返回都会+1,保证递归是有意义的。具体看代码:

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public int maxDepth(TreeNode root) {
        if (root == null){
            return 0;
        }
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        //这一步就告诉我们最后开始返回的时候,每返回一次加一次1
        int max = Math.max(left, right) + 1;
        return max;
    }
}

  

[lintcode]Maximum Depth of Binary Tree

原文:http://www.cnblogs.com/tritritri/p/4856921.html

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