标签:node right return int LeetCode 二叉树 root 节点 left
1. 深度优先
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
return 1+countNodes(root->left)+countNodes(root->right);
}
};
2. 广度优先
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
int count = 0;
auto q = queue<TreeNode*>();
q.push(root);
while (!q.empty()) {
for (int i = 0; i < q.size(); i++) {
auto node = q.front();
q.pop();
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
count++;
}
}
return count;
}
}
3. 深度优先简化计算
通过判断子树是否是完全二叉树,直接计算
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
int left = countLevel(root->left);
int right = countLevel(root->right);
if(left == right)
return countNodes(root->right) + (1<<left);
else return countNodes(root->left) + (1<<right);
}
int countLevel(TreeNode* root){
int level = 0;
while(root){
level++;
root = root ->left;
}
return level;
}
};
4. 二分查找+位运算(看不懂)
点击查看代码
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int level = 0;
TreeNode* node = root;
while (node->left != nullptr) {
level++;
node = node->left;
}
int low = 1 << level, high = (1 << (level + 1)) - 1;
while (low < high) {
int mid = (high - low + 1) / 2 + low;
if (exists(root, level, mid)) {
low = mid;
} else {
high = mid - 1;
}
}
return low;
}
bool exists(TreeNode* root, int level, int k) {
int bits = 1 << (level - 1);
TreeNode* node = root;
while (node != nullptr && bits > 0) {
if (!(bits & k)) {
node = node->left;
} else {
node = node->right;
}
bits >>= 1;
}
return node != nullptr;
}
};
标签:node,right,return,int,LeetCode,二叉树,root,节点,left 来源: https://www.cnblogs.com/929code/p/16519242.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。