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
- [LeetCode] Count Complete Tree Nodes
- leetcode - Count Complete Tree Nodes
- Leetcode: Count Complete Tree Nodes
- [LeetCode]Count Complete Tree Nodes
- LeetCode Count Complete Tree Nodes
- [leetcode] Count Complete Tree Nodes
- leetCode:Count Complete Tree Nodes
- [LeetCode] Count Complete Tree Nodes
- leetcode Count Complete Tree Nodes
- #leetcode#Count Complete Tree Nodes
- leetcode Count Complete Tree Nodes
- LeetCode Count Complete Tree Nodes
- LeetCode - Count Complete Tree Nodes
- leetcode: Count Complete Tree Nodes
- leetcode--Count Complete Tree Nodes
- [LeetCode] Count Complete Tree Nodes
- Leetcode: Count Complete Tree Nodes
- [Leetcode]Count Complete Tree Nodes
- extern "C"解析
- SPOJ-SHPATH - The Shortest Path
- 数字三角形合集
- C语言的低级运算
- 承兑贴息
- Leetcode: Count Complete Tree Nodes
- 线性时间Huffman算法 SDUT 1987
- 关于根据陀螺仪获取加速度和重力感应,计算用户行走的步数算法
- 设计模式-开篇:软件的可维护性和可复用性
- 黑马程序员——ios基础---Objective-C:基础语法
- iOS开发-CoreMotion框架(加速计和陀螺仪)
- hive学习笔记-高级查询
- 关于实体为Date类型的字段,如何用model.find(" date>? ",param)方法进行查询?
- hdu 4007 平行矩形包含点数