222. Count Complete Tree Nodes

Given the root of a complete binary tree, return the number of the nodes in the tree.

According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Design an algorithm that runs in less than O(n) time complexity.

Example 1:

Input: root = [1,2,3,4,5,6]
Output: 6

Example 2:

Input: root = []
Output: 0

My Solutions:

方法1:遍历所有节点

Time: O(n)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int countNodes(TreeNode root) {
         if (root == null) return 0;
         return 1 + countNodes(root.left) + countNodes(root.right);
    }
}

方法2: 利用complete树的性质,一定是从左往右填node。所以先找到树的高度,如果最后一层是满的,说明node的数量是2^height-1。不然则recursively找到最后一个满的位置

Time: O(lgn * lgn)

public int countNodes(TreeNode root) {
    if (root == null) return 0;
    TreeNode left = root, right = root;
    int height = 0;
    while (right != null) {
        left = left.left;
        right = right.right;
        height++;
    }
    
    // 这一层是满的
    if (left == null) return (int) Math.pow(2, height) - 1;
    else return 1 + countNodes(root.left) + countNodes(root.right);
}

Last updated