222. 完全二叉树的节点个数

# 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: Optional[TreeNode]) -> int:
    #     #递归
    #     return self.getNodeCount(root)

    # def getNodeCount(self, cur):
    #     if not cur:
    #         return 0
    #     return self.getNodeCount(cur.left) + self.getNodeCount(cur.right) + 1
        # #层序
        # if not root:
        #     return 0
        # queue = collections.deque([root])
        # nodecounts = 0
        # while queue:
        #     for _ in range(len(queue)):
        #         node = queue.popleft()
        #         nodecounts += 1
        #         if node.left:
        #             queue.append(node.left)
        #         if node.right:
        #             queue.append(node.right)
        # return nodecounts
        #左右深度比较
        if not root:
            return 0
        left = root.left
        right = root.right
        ldeep = 1
        rdeep = 1
        while left:
            ldeep += 1
            left = left.left
        while right:
            rdeep += 1
            right = right.right
        if ldeep == rdeep:
            return 2**ldeep - 1
        return self.countNodes(root.left) + self.countNodes(root.right) + 1

你可能感兴趣的:(python,算法,leetcode)