「Leetcode」104. Maximum depth of binary tree

Problem-solving language:
The general framework of C language thinking is to calculate the depth of the left and right subtrees of the root node of the binary tree, and then compare, the larger one is the maximum depth of the binary tree (remember to add 1, plus the root node level) .
Insert picture description here
Let’s look at my initial solution


int maxDepth(struct TreeNode* root)
{
    if(root==NULL)
    {
        return 0;
    }
    return maxDepth(root->left)>maxDepth(root->right)?maxDepth(root->left)+1:maxDepth(root->right)+1;
}

It seems that there is no big problem on the surface, but in fact there is a big problem. Writing the submission result in this way is beyond the time limit, because in the last line of code, it is actually counted again.

The optimized code is as follows


int maxDepth(struct TreeNode* root)
{
    if(root==NULL)
    {
        return 0;
    }
    int leftDepth=maxDepth(root->left);
    int rightDepth=maxDepth(root->right);
	return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}

Beat 99.71% of users

Guess you like

Origin blog.csdn.net/NanlinW/article/details/96863841