1759. 二叉树的结点

1759. 二叉树的结点 

中文English

给出一棵二叉树,返回其节点数。

样例

样例 1:

输入:
{1,#,2,3}
   1
    \
     2
    /
   3
输出:
3

样例 2:

输入:
{1,2,3}
   1
  / \
 2   3
输出:
3
 
 
输入测试数据 (每行一个参数)如何理解测试数据?

 递归写法:

"""
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: return 0
    
        if 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: return 0
        
        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)

 

posted @ 2020-08-15 19:23  风不再来  阅读(201)  评论(0编辑  收藏  举报