二叉树第三天的内容,递归方面还是得多熟练熟练
104. 二叉树的最大深度
这道题因为二叉树的深度=二叉树最大高度
而根节点的高度就是最大高度,所以我们可以求高度从而求出深度
这里采用的是比较简单的后序遍历
class Solution {
public:
int maxDepth(TreeNode* root) {
//终止条件
if(root == NULL)return 0;
//左右中,后序
int leftdepth = maxDepth(root->left);
int rightdepth = maxDepth(root->right);
int mid = max(leftdepth, rightdepth)+1;
return mid;
}
};
111. 二叉树的最小深度
这道题跟上一道题非常像,但是最小深度的定义是到叶节点的距离,所以假设根节点的左结点为空,你也不能说最小深度为1。所以这道题的问题就是排除特殊情况
这里还是用后序遍历
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;
//左右中,跟上一题很像
int result = 1+min(leftdepth, rightdepth);
return result;
}
};
222. 完全二叉树的节点个数
完全二叉树也是一个二叉树,所以我们可以完全不用管它的性质,当作普通的二叉树进行结点计算
还是后序遍历,依次计数
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL)return 0;
int leftdepth = countNodes(root->left);
int rightdepth = countNodes(root->right);
int mid = leftdepth+rightdepth+1;
return mid;
}
};
当然,这道题目考得应该是完全二叉树的性质,完全二叉树的定义是:
在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2^(h-1) 个节点。
所以如果如果左节点高度=右节点高度,也就是一个满二叉树,我们可以利用2的深度次方-1来计算,但是要排除最后一层不一定是满二叉树的情况
但是哪怕最后有一个结点没满,它的子结点也是两个空,所以也符号满二叉树定义,递归我们可以这么写:
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL)return 0;
TreeNode*left = root->left;
TreeNode*right = root->right;
//方便位运算,初始为0.因为2<<0等于2的一次方
int leftdepth = 0, 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;
}
};