compare the depth between left sub tree and right sub tree. A, If it is equal, it means the left sub tree is a full binary tree B, It it is not , it means the right sub tree is a full binary tree
- 80ms
- 69%
# 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:
if not root:
return 0
left = self.getDepth(root.left)
right = self.getDepth(root.right)
if left==right:
return 2**(left) + self.countNodes(root.right)
else:
return 2**(right) + self.countNodes(root.left)
def getDepth(self, root):
if not root: return 0
return 1+self.getDepth(root.left)