卖萌的弱渣

I am stupid, I am hungry.

Count Complete Tree Nodes

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

A Complete binary tree: is a binary tree in which all interior nodes have two children and all leaves have the same depth or same level

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.

Solution

  • 最后一层可能不满
(Count-Complete-Tree-Nodes.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 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
        lh = 0
        rh = 0
        tmp = root

        # find 极左子树的高度
        while tmp:
            lh += 1
            tmp = tmp.left

        # find 极右子树的高度

        tmp = root
        while tmp:
            rh += 1
            tmp = tmp.right

        if lh == rh:
            return 2**lh -1

        return self.countNodes(root.left) + self.countNodes(root.right) + 1