104.二叉树的最大深度
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:二叉树的高度和深度有啥区别?究竟用什么遍历顺序?很多录友搞不懂 | LeetCode:104.二叉树的最大深度_哔哩哔哩_bilibili
状态:通过
解题思路:可以使用后续遍历的方法,先求出子树的最大高度,再求出整颗树的高度,就得到了二叉树的最大深度。
代码实现:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
int depth1 = maxDepth(root->left);
int depth2 = maxDepth(root->right);
int depth = 1 + max(depth1, depth2);
return depth;
}
};
111.二叉树的最小深度
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:看起来好像做过,一写就错! | LeetCode:111.二叉树的最小深度_哔哩哔哩_bilibili
状态:未通过
代码实现:
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL) return 0;
int leftDepth = minDepth(root->left);
int rightDepth = minDepth(root->right);
if(root->left == NULL && root->right != NULL){
return 1 + rightDepth;
}
if(root -> left != NULL && root->right == NULL){
return 1 + leftDepth;
}
return 1 + min(leftDepth, rightDepth);
}
};
题目难点:容易忽略左孩子或者右孩子为空的情况。
222.完全二叉树的节点个数
题目链接:. - 力扣(LeetCode)
文档讲解:代码随想录
视频讲解:要理解普通二叉树和完全二叉树的区别! | LeetCode:222.完全二叉树节点的数量_哔哩哔哩_bilibili
状态:通过
初步解题思路:使用后序遍历的方法,遍历整个二叉树,进而统计二叉树的节点个数 。
代码实现:
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
int leftNum = countNodes(root->left);
int rightNum = countNodes(root->right);
int result = leftNum + rightNum + 1;
return result;
}
};
看完代码随想录后解题思路:利用完全二叉树的特性来求二叉树的节点数,这样可以不用遍历所有的二叉树节点。
代码实现:
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int leftDepth = 0;
int rightDepth = 0;
while(left){
left = left->left;
leftDepth++;
}
while(right){
right = right->right;
rightDepth++;
}
if(leftDepth == rightDepth){
return (2 << leftDepth) - 1;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};