zoukankan      html  css  js  c++  java
  • 一口气带你刷5道题

    一口气带你刷5道题

    一套代码,(几乎)改都不用改,刷完各种树的各种遍历。

    先说原理:一个栈,栈中每个元素是由一个元组组成,根据进入栈中树的节点需要扮演角色不同,元祖第二个布尔值不同。有个题解讲得很棒。

    原理明白后只需搞懂前序,后面都很简单!

    对于二叉树中的任何一个节点而言,它都有两个角色需要扮演,一个是作为值存储的角色(角色1),另一个角色是作为它所带领的子树的一个代表(角色2)。而我们设置的bool变量,就是为了说明我当前拿到的这个节点,应该是以一个值存储的这种角色对待它(True),还是应该以一个子树的代表这种角色对待它(False),如果是前者,那么就简单的将其所存储的值打印出来,如果是后者,我们需要继续探索由它带领的子树。

    作者:liu-yong-4
    链接:https://leetcode-cn.com/problems/two-sum/solution/xian-xu-zhong-xu-hou-xu-de-fei-di-gui-ban-ben-by-l/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    二叉树前序

    根据栈的特点,先右后左,最后根。第一次进栈代表整棵子树False,还未被访问,第二次进栈代表节点True,再次出栈就要被访问。

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def preorderTraversal(self, root: TreeNode) -> List[int]:
            res =[]
            stack = [] #must have
            if root:
                stack = [(root,False)]
            while stack:
                node,visited= stack.pop()
                if  visited:
                    res.append(node.val)
                else:
                    if node.right:
                        stack.append([node.right,False])
                    if node.left:
                        stack.append([node.left,False])
                    stack.append([node,True]) #前序
            return res
    

    二叉树中序

    中序和后续只需要改节点进栈时机一句代码。

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def preorderTraversal(self, root: TreeNode) -> List[int]:
            res =[]
            stack = [] #must have
            if root:
                stack = [(root,False)]
            while stack:
                node,visited= stack.pop()
                if  visited:
                    res.append(node.val)
                else:
                    if node.right:
                        stack.append([node.right,False])
                    stack.append([node,True])            #中序
                    if node.left:
                        stack.append([node.left,False])
            return res
    

    二叉树后序

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def preorderTraversal(self, root: TreeNode) -> List[int]:
            res =[]
            stack = [] #must have
            if root:
                stack = [(root,False)]
            while stack:
                node,visited= stack.pop()
                if  visited:
                    res.append(node.val)
                else:
                    stack.append([node,True])     #后序
                    if node.right:
                        stack.append([node.right,False])
                    if node.left:
                        stack.append([node.left,False])
            return res
    

    N叉树前序

    只需在二叉树前序基础上,进右左改为逆向进孩子。

    """
    # Definition for a Node.
    class Node:
        def __init__(self, val, children):
            self.val = val
            self.children = children
    """
    class Solution:
        def preorder(self, root: 'Node') -> List[int]:
            res =[]
            stack = [] #must have
            if root:
                stack = [(root,False)]
            while stack:
                node,visited= stack.pop()
                if  visited:
                    res.append(node.val)
                else:
                    for child in node.children[::-1]: #逆向进孩子。
                        stack.append([child,False])
                    stack.append([node,True])          #前序
                    
            return res
    
    

    N叉树后序

    比葫芦画瓢,没什么好说。

    """
    # Definition for a Node.
    class Node:
        def __init__(self, val, children):
            self.val = val
            self.children = children
    """
    class Solution:
        def preorder(self, root: 'Node') -> List[int]:
            res =[]
            stack = [] #must have
            if root:
                stack = [(root,False)]
            while stack:
                node,visited= stack.pop()
                if  visited:
                    res.append(node.val)
                else:
                    stack.append([node,True])          #后序
                    for child in node.children[::-1]: #逆向进孩子。
                        stack.append([child,False])
                    
            return res
    

    2019.08.15

  • 相关阅读:
    正则表达式的三种模式【贪婪、勉强、侵占】的分析
    php实用的文件上传类
    php简单实用的验证码生成类
    phpstorm不安装apache就可以本地测试PHP
    Ajax技术——带进度条的文件上传
    Mybatis 多表查询及查询结果映射
    关于textarea包在div的自适应问题
    Luogu P3200 [HNOI2009]有趣的数列
    群&置换群&burnside
    卡特兰树
  • 原文地址:https://www.cnblogs.com/qizhien/p/11366141.html
Copyright © 2011-2022 走看看