Maximum Depth of Binary Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xinglu31/article/details/24735537
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxDepth(TreeNode root) {
         if(root == null){
            return 0;
        }
        int res = 1;
        int l = maxDepth(root.left);
        int r = maxDepth(root.right);
        return l > r? l + 1:r+ 1;
    }
}

Maximum Depth of Binary Tree

 ,上面代码提交通过,不过之前相似的代码提交不通过:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        int res = 1;
        
            return res + (maxDepth(root.left) > maxDepth(root.right) ? maxDepth(root.left)
                    : maxDepth(root.right));
    }
}

这个结果超时,因为return那里就多执行了两遍遍历,搞到我要上网查过确认。。。

没有更多推荐了,返回首页