如果完全二叉树,最左和最右的路径是一样长的。利用这个递归。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def countNodes(self, root: TreeNode) -> int:
leftHeight = self.countLeftHeight(root)
rightHeight = self.countRightHeight(root)
if leftHeight == rightHeight:
return 2 ** leftHeight - 1
else:
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
def countLeftHeight(self, root: TreeNode) -> int:
height = 0
while root is not None:
height += 1
root = root.left
return height
def countRightHeight(self, root: TreeNode) -> int:
height = 0
while root is not None:
height += 1
root = root.right
return height
[leetcode]Count Complete Tree Nodes
原文:https://www.cnblogs.com/lautsie/p/12285633.html