Time limited when I change to simplified code

  • 10
    if (root == NULL)
    	return 0;
    int leftDept = maxDepth(root->left);
    int rightDept = maxDepth(root->right);
        if (leftDept >= rightDept)
    	return leftDept+1;
    	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;

  • 46
    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 {
        int maxDepth(TreeNode *root) {
            return root ? 1 + max(maxDepth(root->left), maxDepth(root->right)) : 0;

  • 0

    awesome code!

  • 0

    Great solution!

  • 6

    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));

  • 0

    where is the function max

  • 1

    too many maxDepths have been used in the second one.

Log in to reply

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