目录
LeeCode 104.二叉树的最大深度
LeeCode 111.二叉树的最小深度
LeeCode 222.完全二叉树的节点个数
基础思路
进阶思路
LeeCode 104.二叉树的最大深度
思路:使用后序遍历求根结点的高度,根结点的高度就是二叉树的最大深度。
class Solution {
public:
int maxDepth(TreeNode* root) {
return getdepth(root);
}
int getdepth(TreeNode* node) {
if (node == NULL) return 0;
int leftdepth = getdepth(node->left);
int rightdepth = getdepth(node->right);
return 1 + max(leftdepth,rightdepth);
}
};
LeeCode 111.二叉树的最小深度
思路: 最小深度是根结点到最近的叶子结点的最短路径上的结点数量,通过后序遍历,将深度向上传,且每次都取较小值。另外,排除左子树/右子树为空的情况,即为答案。
class Solution {
public:
int minDepth(TreeNode* root) {
return getdepth(root);
}
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;
}
};
LeeCode 222.完全二叉树的节点个数
222. 完全二叉树的节点个数 - 力扣(LeetCode)
基础思路:
像普通二叉树一样遍历整棵树,求出节点个数。
class Solution {
private:
int getNodesNum(TreeNode* cur) {
if (cur == NULL) return 0;
int leftNum = getNodesNum(cur->left);
int rightNum = getNodesNum(cur->right);
int treeNum = leftNum + rightNum + 1;
return treeNum;
}
public:
int countNodes(TreeNode* root) {
return getNodesNum(root);
}
};
时间复杂度:O(n) 空间复杂度:O(log n)
进阶思路:
利用满二叉树节点个数 = 2^(高度) - 1 的性质,若当前节点的左右子树为满二叉树,求出高度后用公式计算节点数。
判断是否为满二叉树:在完全二叉树中,递归向左遍历的深度等于递归向右遍历的深度。
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int ldepth = 0, rdepth = 0;
while (left) {
left = left->left;
ldepth ++;
}
while (right) {
right = right->right;
rdepth ++;
}
if (ldepth == rdepth) {
return (2 << ldepth) - 1;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};
时间复杂度:O(log n x log n) 空间复杂度:O(log n)