一、题目:
计算完全二叉树节点的个数
二、参考博客
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