首页 > 其他 > 详细

1759. 二叉树的结点

时间:2020-08-15 22:53:22      阅读:84      评论:0      收藏:0      [点我收藏+]

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)

 

1759. 二叉树的结点

原文:https://www.cnblogs.com/yunxintryyoubest/p/13509980.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!