222 Count Complete Tree Nodes

使用递归自己调用自己的方法进行解决。

Python

# 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
        if not root.left and not root.right:
            return 1
        return self.countNodes(root.left) + self.countNodes(root.right) + 1

results matching ""

    No results matching ""