Day16 二叉树第三天
LeetCode 104.二叉树的最大深度【后序遍历】
求深度用的是后序遍历,是考虑到根节点的高度就是最大深度,所以求深度可以转化为求高度。
class Solution {
public:
int getDepth(TreeNode* root){
if(!root) return 0;
int left=getDepth(root->left);
int right=getDepth(root->right);
int depth=1+max(left,right);
return depth;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
};
LeetCode 111. 二叉树的最小深度【后序遍历】
求最小深度时要注意的一点是,如果一个节点左子树或右子树为空,那么它就不是叶子结点,所以不能单纯的把左右子树深度的最小值+1,要分开讨论。
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == nullptr) return 0;
if(root->left == nullptr) return minDepth(root->right) + 1;
if(root->right == nullptr) return minDepth(root->left) + 1;
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
};
LeetCode 222. 完全二叉树的节点个数
此题当然可以用普通的求节点数量来做。
但我们还是要用完全二叉树的特性来方便我们做题。
思路就是利用完全二叉树节点相连的特性,如果一棵树从左遍历到底和从右遍历到底的深度相等,那么他就是完全二叉树,他的节点个数等于2树的深度-1。如果不等, 再遍历到下层的子树。
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
TreeNode* left=root->left;
TreeNode* right=root->right;
int leftHeight=0,rightHeight=0;
while(left){
left=left->left;
leftHeight++;
}
while(right){
right=right->right;
rightHeight++;
}
if(leftHeight==rightHeight)
return (2<<leftHeight)-1;
return countNodes(root->left)+countNodes(root->right)+1;
}
};
加油呀,别输给二叉树了。