Complete Tree

A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.


CompleteBinary

lc#222 Count Complete Tree Nodes
compute the number of nodes in complete tree

public int countNodes(TreeNode root) {
    if(root == null) return 0;

    int height = 0;
    TreeNode left = root.left, right = root.right;
    while(left != null && right != null) {
        height++; 
        left = left.left;
        right = right.right;
    }
    
    return left == right ? (1 << height + 1) - 1 : 1 + countNodes(root.left) + countNodes(root.right);
} 

你可能感兴趣的:(Complete Tree)