终于AC了,一开始用三目运算符调用四次递归,直接超时
超时代码:
/**
* 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) {
if(root != null){
return maxDepth(root.right) >= maxDepth(root.left) ? maxDepth(root.right)+1: maxDepth(root.left)+1;
}
return 0;
}
}
AC代码:
/**
* 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) {
if(root != null){
return Math.max(maxDepth(root.right)+1, maxDepth(root.left)+1);
}
return 0;
}
}
c代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root){
if(root == NULL) return 0;
return fmax(maxDepth(root->right)+1, maxDepth(root->left)+1);
}
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;
return max(maxDepth(root->right)+1, maxDepth(root->left)+1);
}
};