<h3><a title="题目描述" href="https://leetcode-cn.com/problems/count-complete-tree-nodes">题目描述</a></h3>
![file](https://i.loli.net/2020/11/24/w7Gj2E6DcXdTq3Q.png)
<h4>方法一</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="java">
//未用到完全二叉树性质
class Solution {
public int countNodes(TreeNode root) {
if(root==null){
return 0;
}
int res = 0;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(queue.size()!=0){
TreeNode node = queue.remove();
res+=1;
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
return res;
}
}
</pre>
<p> </p>
<h4>方法二:二分+位运算</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="java">
class Solution {
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
int level = 0;
TreeNode node = root;
while (node.left != null) {
level++;
node = node.left;
}
int low = 1 << level, high = (1 << (level + 1)) - 1; //最少2^level个,最多2^(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;
}
public boolean exists(TreeNode root, int level, int k) {
int bits = 1 << (level - 1);
TreeNode node = root;
while (node != null && bits > 0) {
if ((bits & k) == 0) {
node = node.left;
} else {
node = node.right;
}
bits >>= 1;
}
return node != null;
}
}
</pre>
<p> </p>
Leetcode222 完全二叉树的节点个数