104. Maximum Depth of Binary Tree

来源:互联网 发布:java冒烟测试怎么做 编辑:程序博客网 时间:2024/06/05 04:12

题目很简单,是求一个二叉树的最大层数,首先思路就是用迭代的方法,左子树的长度和右子树长度比较之后取最大值,然后加一即为二叉树的最大层数。

java代码如下(运行时间1ms,并不是很快)

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

原创粉丝点击