Leetcode222 完全二叉树的节点个数

题目描述

file

方法一

//未用到完全二叉树性质
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;
    }
}

 

方法二:二分+位运算

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;
}

}