题目:
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.
分析:
此题用递归的方式做非常简单,虽然一次性就通过了,但是之所以记下来,是因为还有一些细节自己处理的并不完善,说明了思考应该更加周到而且不冗余。
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int max(int a, int b)
{
return a > b ? a : b;
}
int maxDepth(TreeNode *root) {
if(root == NULL)return 0;
else if ((root->left == NULL) && (root->right == NULL))return 1;
else if (root->left == NULL)return 1+maxDepth(root->right);
else if (root->right == NULL)return 1+maxDepth(root->left);
else
{
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
}
};
自我分析:
其实代码中那三个else if语句可以完全省略,因为当左子树或者右子树为空后,调用madDepth函数,本身在最开始的时候会判断是否为NULL,如果是,直接返回。以后思考的时候注意,不仅仅要全面,同时要做到不冗余。另外,从执行效率的角度上,不是很建议用上述判断左右子树谁的深度最大,因为函数的调用存在开销的,将左右字数的深度存放于一个temp值中,用temp值进行比较效率更高。
优化后的代码:
int maxDepth(TreeNode *root) {
if(root == NULL)return 0;
int ltmp = maxDepth(root->left);
int rtmp = maxDepth(root->right);
return 1+(ltmp>rtmp?ltmp:rtmp);
}