leetcode-222
来源:互联网 发布:c语言库函数大全 编辑:程序博客网 时间:2024/06/16 14:34
一、题目:
计算完全二叉树节点的个数
二、参考博客
https://segmentfault.com/a/1190000003818177
http://blog.csdn.net/xudli/article/details/46385011
三.解题思路
完全二叉树的一个性质是,如果左子树最左边的深度,等于右子树最右边的深度,说明这个二叉树是满的,即最后一层也是满的,则以该节点为根的树其节点一共有2^h-1
个。如果不等于,则是左子树的节点数,加上右子树的节点数,加上自身这一个。
四、代码
# 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 getLeft(self, root):
count = 0
while root:
if root.left:
count += 1
root = root.left
return count
def getRight(self, root):
count = 0
while root:
if root.right:
count += 1
root = root.right
return count
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
l = self.getLeft(root)
r = self.getRight(root)
if l == r:
return (2 << l) - 1
else:
return self.countNodes(root.left) + self.countNodes(root.right) + 1
- leetcode-222
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- 最新力作:《Android自定义组件开发详解》
- 九度-题目1054:字符串内排序
- 产品经理的灵魂所在
- 【Linux运维入门】SonarQube和Jenkins的集成之路
- java基础--浅析java中序列化机制
- leetcode-222
- 第二章习题第七题
- 接口与抽象类
- CodeForces 266E More Queries to Array... 线段树
- mysqldump使用
- Jquery滑块展示
- 使用git和github管理自己的项目---真实开发环境的策略
- 6. 自定义函数
- JSP学习笔记五之application和page对象