zoukankan      html  css  js  c++  java
  • 给定一个 N 叉树,返回其节点值的前序遍历和后序遍历

    例如,给定一个 3叉树 :

     

    返回其前序遍历: [1,3,5,6,2,4]

    """
    # Definition for a Node.
    class Node(object):
        def __init__(self, val=None, children=None):
            self.val = val
            self.children = children
    """
    
    class Solution(object):
        def preorder(self, root):
            """
            :type root: Node
            :rtype: List[int]
            """
            if root is None:
                return []
            
            stack, output = [root, ], []            
            while stack:
                root = stack.pop()
                output.append(root.val)
                stack.extend(root.children[::-1])
                    
            return output

    后序遍历

    """
    # Definition for a Node.
    class Node(object):
        def __init__(self, val=None, children=None):
            self.val = val
            self.children = children
    """
    
    class Solution(object):
        def postorder(self, root):
            """
            :type root: Node
            :rtype: List[int]
            """
            stack,ouput = [root,],[]
            while stack:
                root = stack.pop()
                if root:
                    ouput.append(root.val)
                else:
                    return
                for i in root.children:
                    stack.append(i)
            return ouput[::-1]
  • 相关阅读:
    最后一次不用看脸的日子
    经典算法_指针
    #include <process.h>
    经典算法_文件
    stdin、stdout、stderr
    经典算法_位运算
    经典算法_结构体
    经典算法_字符串
    #include <string.h>
    #include <stdio.h>
  • 原文地址:https://www.cnblogs.com/ghl666/p/13520886.html
Copyright © 2011-2022 走看看