222. 完全二叉树的节点个数

题目:

思路:

【1】利用层数来计算个数的大致范围,然后利用二分来确定个数的准确值。

代码展示:

//时间0 ms 击败 100%
//内存45 MB 击败 5.4%
//时间复杂度和空间复杂度都是 O(n)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int count = 0;
    public int countNodes(TreeNode root) {
        if (root == null) return count;
        count++;
        countNodes(root.left);
        countNodes(root.right);
        return count;
    }
}

//时间0 ms 击败 100%
//内存44.9 MB 击败 14.49%
//时间复杂度:O(log^2 n)。
//空间复杂度:O(1)。只需要维护有限的额外空间。
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;
        }
        // 然后因为完全二叉树的特性,节点个数必然在【2^(k-1)+1 , 2^k - 1】,k为层数【最低是1】
        // 然后利用二分法的方式查找出最后节点所在的位置
        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;
    }

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

 

posted @ 2023-07-12 12:44  忧愁的chafry  阅读(13)  评论(0)    收藏  举报