昨天晚上做这道题目用C++很容易就通过了,然而用java始终没能够提交通过,思考了一晚上加今天一上午,终于将java语言的提交通过了。代码如下:
/**
* Definition for a binary tree node.* 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;
else if (root.left == null && root.right == null)
return 1;
else {
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return 1 + (left > right ? left : right);
}
}
}