LeetCode 222 - Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
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 2h nodes inclusive at the last level h.

public int countNodes(TreeNode root) {
    if(root == null) return 0;
    int hl = 0, hr = 0;
    TreeNode l = root, r = root;
    while(l != null) {
        hl++;
        l = l.left;
    }
    while(r != null) {
        hr++;
        r = r.right;
    }
    if(hl == hr) {
        return (int)Math.pow(2, hl)-1;
    }
    return 1+countNodes(root.left)+countNodes(root.right);
}

猜你喜欢

转载自yuanhsh.iteye.com/blog/2217471