"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of the binary tree
@return: the number of nodes
"""
def __init__(self):
self.visted = set()
def getAns(self, root):
# Write your code here
if not root: return0if id(root) not in self.visted:
self.visted.add(id(root))
self.getAns(root.left)
self.getAns(root.right)
return len(self.visted)
非递归写法:
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of the binary tree
@return: the number of nodes
"""
def getAns(self, root):
# Write your code here
#非递归写法
if not root: return0
stack = [root]
visted = set()
while stack:
pop_node = stack.pop()
if id(pop_node) not in visted:
visted.add(id(pop_node))
if pop_node.left:
stack.append(pop_node.left)
if pop_node.right:
stack.append(pop_node.right)
return len(visted)