题目
给定一棵完全二叉树的根节点root,返回这棵树的节点个数。如果完全二叉树的节点数为N,请实现时间复杂度低于O(N)的解法。
给定树的根结点root,请返回树的大小。
思路
二分查找。统计根节点最左节点的深度。当左边深度和右边深度相同时,说明左边是完全二叉树,递归遍历右边,否则右边是完全二叉树,递归遍历左边。
代码
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class CountNodes:
def getDepth(self, root):
count = 0
while root:
count += 1
root = root.left
return count
def count(self, root):
# write code here
if not root:
return 0
res = 0
left_depth = 0; right_depth = 0
left_depth = self.getDepth(root.left)
right_depth = self.getDepth(root.right)
if left_depth == right_depth:
return 2 ** left_depth + self.count(root.right)
else:
return 2 ** right_depth + self.count(root.left)