leetcode/src/s0222_count_complete_tree_nodes.cpp
2023-01-31 11:05:33 +08:00

39 lines
1.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "s0222_count_complete_tree_nodes.hpp"
// DFS O(n)
int S0222::countNodes1(TreeNode* root) {
if (root == nullptr) return 0;
return countNodes1(root->left) + countNodes1(root->right) + 1;
}
// BFS O(n)
int S0222::countNodes2(TreeNode* root) {
queue<TreeNode*> q;
int sum{0};
if (root) q.push(root);
TreeNode* front;
int size{0};
while (!q.empty()) {
size = q.size();
for (int i{0}; i < size; ++i) {
front = q.front();
q.pop();
++sum;
if (front->left) q.push(front->left);
if (front->right) q.push(front->right);
}
}
return sum;
}
// 利用满二叉树的特性
// 假设满二叉树一共有 h 层,那么总节点个数的范围应该是 [2^(h - 1), 2^h - 1] 之间
// 也就是最后一层满和没满的区别
// 所以可以在这个范围内用二分法搜索
// 如何判断第 kkk 个节点是否存在呢?如果第 kkk 个节点位于第 hhh 层,则 kkk
// 的二进制表示包含 h+1h+1h+1 位,其中最高位是
// 111其余各位从高到低表示从根节点到第 kkk 个节点的路径000
// 表示移动到左子节点111 表示移动到右子节点。通过位运算得到第 kkk
// 个节点对应的路径,判断该路径对应的节点是否存在,即可判断第 kkk
// 个节点是否存在。