• 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)
  • 相关阅读:
    Linux网卡上添加多个IP
    TCP_Wrappers基础知识介绍
    工作、生活、思考、人生、经验、总结
    网络层安全
    centos7.0 安装nginx
    linux 下配置jdk
    yii2.0 中的队列
    centos7.0 activemq的安装
    solrCloud
    线性顺序表
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13509980.html
Copyright © 2020-2023  润新知