[leetcode]_Maximum Depth of Binary Tree

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

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

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

代码:

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

 昨天AC看的网络代码,今日回顾了一下,提交下面代码,顺利AC。

public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        
        return Math.max(maxDepth(root.left) , maxDepth(root.right)) + 1;
    }

跟上面的原理一样,但这样写更清晰,感觉自己真的在进步啊。o(≧v≦)o~~好棒

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