C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL) return 0;
if(root->left!=NULL||root->right!=NULL)
return max(maxDepth(root->left),maxDepth(root->right))+1;
else
return 1;
}
};
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;
if(root.left!=null||root.right!=null)
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
else return 1;
}
}
Javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if(root===null) return 0;
if(root.left!==null||root.right!==null)
{
var leftHeight=maxDepth(root.left);
var rightHeight=maxDepth(root.right);
return leftHeight>rightHeight? leftHeight+1:rightHeight+1;
}
else
return 1;
};
最优解
思路一样,写法比较简洁
Java
public class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}
}