Leetcode: Count Complete Tree Nodes

来源:互联网 发布:桌面美女跳舞软件 编辑:程序博客网 时间:2024/06/05 15:31

Get idea from 西施豆腐渣.


Question

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.

Hide Tags Tree Binary Search
Have you met this question in a real interview? Yes No
Discuss


Analysis

If write down the answer as wrong solution described below, the time will exceeded. How to cut down its time ? We can get the number before counting the whole tree, by comparing the left height and right height. This is the smart way to save time.


Solution

wrong answer (Time Limit Exceeded)

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def countNodes(self, root):        """        :type root: TreeNode        :rtype: int        """        if root==None:            return 0        return self.helper(root)    def helper(self, root):        if root==None:            return 0        return 1 + self.helper(root.left) + self.helper(root.right)

My Solution

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def countNodes(self, root):        """        :type root: TreeNode        :rtype: int        """        if root==None:            return 0        lh = self.getlh(root)        rh = self.getrh(root)        if lh==rh:            return 2**lh-1        else:            return 1 + self.countNodes(root.left) + self.countNodes(root.right)    def getlh(self, root):        h = 0        while root!=None:            h += 1            root = root.left        return h    def getrh(self, root):        h = 0        while root!=None:            h += 1            root = root.right        return h
0 0
原创粉丝点击