一、二叉树的最大深度
思路
二叉树的深度:任意一个结点到根节点的距离(前序遍历)
二叉树的高度:任意一个结点到叶子结点的距离(后序遍历)
根节点的高度就是二叉树的最大深度,所以用后序遍历求根节点的高度
代码实现
class Solution {
public:
int getdepth(TreeNode* node) {
if(node == NULL) return 0;
int leftdepth = getdepth(node->left); // 左
int rightdepth = getdepth(node->right); // 右
int depth = 1 + max(leftdepth,rightdepth); // 中
return depth;
}
int maxDepth(TreeNode* root) {
return getdepth(root);
}
};
二、二叉树的最小深度
思路
用根节点的最小高度(后序遍历)来求符合题目要求的最小深度
不能直接把二叉树的最大深度中的max换成min,否则会多记录某个子树为空的情况,不满足题意
代码实现
在这里插入代码片class Solution {
public:
int getdepth(TreeNode *node){
if(node == NULL) return 0;
int leftdepth = getdepth(node->left);
int rightdepth = getdepth(node->right);
if(node->left == NULL && node->right != NULL) {
return 1 + rightdepth;
}
if(node->left != NULL && node->right == NULL) {
return 1 + leftdepth;
}
int result = 1 + min(leftdepth,rightdepth);
return result;
}
int minDepth(TreeNode* root) {
return getdepth(root);
}
};
三、完全二叉树的结点个数
思路
后序遍历,判断子树是否为满二叉树,如果是满二叉树(往左遍历的深度等于往右遍历的深度),直接用公式计算,返回给上一层,如果不是满二叉树,继续向下遍历。
结点数量=左子树结点数量+右子树数量+1
代码实现
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
TreeNode* left = root->left;
TreeNode* right= root->right;
int leftDepth = 0, rightDepth = 0;
while(left) {
left = left->left;
leftDepth++;
}
while(right) {
right = right->right;
rightDepth++;
}
if(leftDepth == rightDepth) {
return (2 << leftDepth) - 1; //2<<1,相当于2^2,所以leftDepth初始为0
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};