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.
题意
给定一个二叉树,求二叉树的深度
注意
二叉树的最大深度定义:是从根节点到叶子结点中的最长路径。
二叉树天然具有递归结构。
思路
先找根节点的左子树深度,再找右子树的深度,比较左右子树深度,返回大的一个
递归的去找,左子树又分左子树右子树。
体会递归的巧妙,一个大问题能够拆分成很多类似大问题解决方案的小问题
代码
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
int leftmaxDepth = maxDepth(root->left); //已经获取了左子树的深度
int rightmaxDepth = maxDepth(root->right);//再获取右子树的深度
return max(leftmaxDepth,rightmaxDepth)+1; //比较之后选大的,在加上当前结点+1
}
};
结果
、
111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
题意
给定一个二叉树,找到二叉树最小的深度
题意
二叉树的最小深度:是从根节点到叶子结点中的最短路径。
思路
若类似104那样做会怎么样。尽管思路大致相同
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
int leftmaxDepth = maxDepth(root->left); //已经获取了左子树的深度
int rightmaxDepth = maxDepth(root->right);//再获取右子树的深度
return min(leftmaxDepth,rightmaxDepth)+1; //比较之后选大的,在加上当前结点+1
}
};
从结果中我们可以看出,当根节点的某一子树为NULL时,会保存为0.
代码
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL)
return 0;
//注意看题意,是从根节点到叶子节点的最短路径长度
//如果不加两个if判断,当树只有两层,其中一侧还是NULL,那么比较判断min(0,1)会返回1
//如果一开始从哪里进入递归,最终就会从哪里出来,然后返回,所以这里从根节点开始分了三种情况
//1.根节点的左孩子为空
//2.根节点的右孩子为空
//3.根结点的左右孩子不为空
if(root->left == NULL)
{
//当结点的左孩子为空,就去找右孩子的深度
return 1+minDepth(root->right);
}
if(root->right == NULL)
{
return 1+minDepth(root->left);
}
int leftminDe = minDepth(root->left);
int rightminDe = minDepth(root->right);
return min(leftminDe,rightminDe)+1;
}
};