码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]_Maximum Depth of Binary Tree

时间:2014-05-14 23:07:14      阅读:373      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   c   

第三道树的题目,我还是不会,我擦,怎么递归算法还是不能很好理解。看来还得好好研究下递归算法。

题目:求一棵树的最大深度。

思路:递归地求取左子树最大深度 和 右子树最大深度,返回较大值即为 整棵树的 最大深度。

代码:

bubuko.com,布布扣
public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        
        int leftHeight = 1,rightHeight = 1;
        if(root.left != null) leftHeight += maxDepth(root.left);
        if(root.right != null) rightHeight += maxDepth(root.right);
        if(leftHeight > rightHeight) return leftHeight;
        else return rightHeight;
    }
bubuko.com,布布扣

 

 

[leetcode]_Maximum Depth of Binary Tree,布布扣,bubuko.com

[leetcode]_Maximum Depth of Binary Tree

标签:style   blog   class   code   java   c   

原文地址:http://www.cnblogs.com/glamourousGirl/p/3728612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!