题目
Given a complete binary tree, count the number of nodes.
Note:
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example:
Input:
1
/ \
2 3
/ \ /
4 5 6
Output: 6
树的递归
二叉树的遍历,先处理根结点后递归子树。
python 代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
return 1+self.countNodes(root.left)+self.countNodes(root.right)
完全二叉树递归
利用完全二叉树的性质,完全二叉树从满二叉树的右边开始缺少结点。满二叉树一定是完全二叉树,完全二叉树不一定是满二叉树。
如果是满二叉树,那么结点数就与树的高度相关:2^h-1。
如果完全二叉树缺少的最后一个结点在右边,那么对于根的左子树是满二叉树,对于其右子树是完全二叉树,且左右子树的高度相等;如果完全二叉树缺少的最后一个结点在左边,那么左子树的高度等于右子树的高度+1,且对于根的左子树是完全二叉树,对于其右子树是满二叉树。
python 代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
lHeight = self.getHeight(root.left)
rHeight = self.getHeight(root.right)
if lHeight == rHeight:
return (1<<lHeight) + self.countNodes(root.right)
if lHeight != rHeight:
return self.countNodes(root.left) + (1<<rHeight)
def getHeight(self,root):
if not root:
return 0
return self.getHeight(root.left)+1