222. 完全二叉树的节点个数 - 力扣(LeetCode) (leetcode-cn.com)
完全二叉树结点个数
递归(遍历法)
-
当前树结点个数 = 左树 + 右树 + 1
-
隐含了后序遍历
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) return 0;
//先左 后右 最后中(+1)
return 1 + countNodes(root->left) + countNodes(root->right);
}
};
非递归(遍历法)
class Solution {
public:
int countNodes(TreeNode* root) {
int count = 0;
if (!root) return count;
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; ++i) {
TreeNode* node = que.front();
que.pop();
++count;
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return count;
}
};
递归(按性质解决)
- 完全二叉树定义及性质
- 满二叉树结点个数 = 2depth - 1
- 单个结点 也可以视为 满二叉树
- 隐含了后序遍历
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) 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;
}
};
本文探讨了如何使用递归和非递归方法计算完全二叉树的节点总数,包括两种遍历方式:后序遍历的递归实现和层序遍历的非递归实现,以及利用完全二叉树性质的简化算法。
5391

被折叠的 条评论
为什么被折叠?



