222. Count Complete Tree Nodes

Given acompletebinary tree, count the number of nodes.

Definition of a complete binary tree fromWikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2hnodes inclusive at the last level h.

tag: binary tree

/**
 * 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;

        int h = getHeight(root);

        return getHeight(root.right) + 1 == h ? (1 << h - 1) + countNodes(root.right) : (1 << h - 2) + countNodes(root.left);
    }

    private int getHeight(TreeNode root){
        return root == null ? 0 : 1 + getHeight(root.left);
    }
}

results for ""

    No results matching ""