zoukankan      html  css  js  c++  java
  • 590. N叉树的后序遍历



    # 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]
            """
            res = []
            if not root:
                return res
            stack = [root]
            while stack:
                curr = stack.pop()
                res.append(curr.val)
                stack += curr.children
            return res[::-1]
    

    方法二:递归

    class Solution(object):
        # 递归
        def postorder(self, root):
            """
            :type root: Node
            :rtype: List[int]
            """
            res = []
            if not root:
                return res
            # 递归遍历子树
            for tNode in root.children:
                res += self.postorder(tNode)
            # 加根节点
            res.append(root.val)
            return res
    
  • 相关阅读:
    WSGI原理
    主从数据库
    mysql高级
    记录
    获取当前时间
    sql注入和防sql注入
    python操作MySQL
    修改Windows10 命令终端cmd的编码为UTF-8
    MySQL查询
    MySQL数据库操作
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13585864.html
Copyright © 2011-2022 走看看