给出一个完全二叉树,求出该树的节点个数。
说明:
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
示例:
输入:
1
/
2 3
/ \ /
4 5 6
输出: 6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-complete-tree-nodes
思路:
1.先递归计算出完全二叉树的高度h,除了最后一层叶子结点外,前h-1层的结点总数为2^(h-1)-1。
2.接着计算最后一层叶子结点个数。判断是叶子结点的条件为:该结点的左结点为空且右结点也为空。
这里需要增加一个条件:当前高度level。因为倒数第二层也可能会出现叶子结点,而我们只需要计算最后一层结点,倒数第二层的结点在第一步已经计算进去了,如果不增加当前层高度为level=h这个判断的话会多计算一次倒数第二层的叶子结点。
# 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 not root: #计算没有节点的情况
return 0
def height(tree): #计算树的高度
if not tree:
return 0
else:
return max(height(tree.left),height(tree.right))+1
self.h=height(root) #h为树的高度
self.count=0
#最后一层节点个数
def nodecount(tree , level):
if not tree:
return 0
if not tree.left and not tree.right and level==self.h:
self.count+=1
nodecount(tree.left,level+1) #左节点的递归
nodecount(tree.right,level+1) #右节点的递归
return self.count
c=nodecount(root,1)
allnodes=pow(2,self.h-1)-1+c
return allnodes