题目
给出一个完全二叉树,求出该树的节点个数。
解法
- 最简单基础的方法,直接统计
# 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 countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
return 1+self.countNodes(root.left)+self.countNodes(root.right)
- 利用完全二叉树的特点
解法来源:https://leetcode-cn.com/problems/count-complete-tree-nodes/solution/chang-gui-jie-fa-he-ji-bai-100de-javajie-fa-by-xia/
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
Node = 0
if root is None:
return 0
# 统计左右子树的层数
left = self.countLevel(root.left)
right = self.countLevel(root.right)
# 当左右层数相等,左子树为完全二叉树, 计算左子树的层数, 进一步统计右子树的结点数
if left == right:
Node += pow(2, left) + self.countNodes(root.right)
# 当左右层数不相等, 右子树为完全二叉树, 计算右子树的层数, 进一步统计左子树结点数
else:
Node += pow(2, right) + self.countNodes(root.left)
return Node
# 非递归,速度更快,更合理
def countLevel(self, root):
Level = 0
while root is not None:
Level += 1
root = root.left
return Level
# 递归统计方法:其实没必要用递归
def countLevel(self, root):
if root is None:
return 0
else:
return max([self.countLevel(root.left), self.countLevel(root.right)])+1
在python里面,如果用了太多递归,第二种方法的耗时会比第一种还长。