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.

解题方法

  1. 首先计算leftmost和rightmost的高度
  2. 如果rightmost和leftmost一样高,说明这棵树是full complete binary tree,那个node的数量就是2 ^ 高度 - 1
  3. 如果不是,就recursive计算左右字数的number, 再加上1(root)

Solution

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def countNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        hL = 1
        hR = 1
        head = root
        #get leftmost height
        while head.left:
            hL += 1
            head = head.left
        head = root
        #get rightmost height
        while head.right:
            hR += 1
            head = head.right

        if hL == hR:
            return 2 ** hL - 1

        leftNum = self.countNodes(root.left)
        rightNum = self.countNodes(root.right)

        return leftNum + rightNum + 1

Reference