/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
int max=0;
if(root==null)
return 0;
if(root.left==null){
max=Math.max(1,maxDepth(root.right)+1);
return max;
}
if(root.right==null){
max=Math.max(maxDepth(root.left)+1,1);
return max;
}
max=Math.max(maxDepth(root.left)+1,maxDepth(root.right)+1);
return max;
}
}
还是官方的写的更简略
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}
}