104. Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its depth = 3.
题目:求二叉树的最大深度
思路:递归方法,先对几种特殊的二叉树判断,再返回左子树、右子树最大深度+1即可。
看到题目马上动手写出了下面的代码。超时过不了。
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
else if(root->left == NULL&&root->right!=NULL)
return maxDepth(root->right)+1;
else if(root->right == NULL&&root->left!=NULL)
return maxDepth(root->left)+1;
else
return maxDepth(root->left)>maxDepth(root->right)?maxDepth(root->left)+1:maxDepth(root->right)+1;
}
}; //程序正确,LeetCode提交超时了
于是对代码进行了一些精简,发现左子树、右子树的深度计算一次就可以了,而我的程序中最后的return语句计算多了。对于耗时的步骤,提前将结果保留,是一种提高程序性能的好办法。一种常见的就是for(int i=0;i<vec.size();i++),应该提前int length=vec.size(),再进行循环。因此本体修改后的代码:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
else
{
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return left>right?left+1:right+1;
}
}
}; //这个递归可以通过,通过变量给函数记录结果,可以省去多次递归