# Time limited when I change to simplified code

• ``````if (root == NULL)
return 0;
int leftDept = maxDepth(root->left);
int rightDept = maxDepth(root->right);
if (leftDept >= rightDept)
return leftDept+1;
else
return rightDept+1;
``````

it accepted when I use above code, but it show time limited when use following code. does anybody know why?

``````if (root == NULL)
return 0;
return maxDepth(root->left)>maxDepth(root->right) ? maxDepth(root->left)+1 : maxDepth(root->right)+1;``````

• ``````maxDepth(root->left)>maxDepth(root->right) ? maxDepth(root->left)+1 : maxDepth(root->right)+1;
``````

This code segment is inefficient because it'll invoke maxDepth one more time than your accepted code.
For example, if the expression before "?" is true, the compiler has to recompute the value of `maxDepth(root->left)`.

``````class Solution {
public:
int maxDepth(TreeNode *root) {
return root ? 1 + max(maxDepth(root->left), maxDepth(root->right)) : 0;
}
};``````

• awesome code!

• Great solution!

• However, if you do want to simplified your code, you may do it in the following way:

``````public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return (Math.max(maxDepth(root.left)+1, maxDepth(root.right)+1));
}}``````

• where is the function max

• too many maxDepths have been used in the second one.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.