题目要求:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7返回它的最大深度 3 。
思路一:
计算二叉树的深度首先需要对比左子树与右子树的深度,如果左子树深度>右子树深度,那么接下来的遍历就从左子树开始。同时在每一次遍历的结束后,需要返回这一次计算深度的值,并且累加。
代码实现:
#include<stdio.h>
struct TreeNode
{
struct TreeNode* left;
struct TreeNode* right;
int val;
};
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;
}
以上程序对一般的树来说可以满足计算深度,但当树的结点数量极大时,会超出运行时间限制,也就是说这个递归算法的计算深度效率不够高。
return maxDepth(root->left)>maxDepth(root->right)?maxDepth(root->left)+1:maxDepth(root->right)+1;
问题:
语句在每一次递归调用的时候都需要重复计算左子树与右子树的深度,导致运算时间累计过长。
所以设置变量保存每一次调用后计算出的左子树深度与右子树深度。
代码实现:
#include<stdio.h>
struct TreeNode
{
struct TreeNode* left;
struct TreeNode* right;
int val;
};
//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;
//}
int maxDepth(struct TreeNode* root)
{
if (root == NULL)
{
return 0;
}
int leftdeep = maxDepth(root->left);
int rightdeep = maxDepth(root->right);
return leftdeep > rightdeep ? leftdeep + 1 : rightdeep + 1;
}