LeetCode Algorithm 589. N 叉树的前序遍历

Posted Alex_996

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Algorithm 589. N 叉树的前序遍历相关的知识,希望对你有一定的参考价值。

589. N 叉树的前序遍历

Ideas

二叉树的前序遍历模板,拿过来稍微一改就完事了。

def preorderTraversalLoop(node):
    if not node:
        return
    stack = [node]  # list 模拟 stack
    while stack:
        tmp = stack.pop()
        print(tmp.value, end=' ')
        if tmp.right:
            stack.append(tmp.right)
        if tmp.left:
            stack.append(tmp.left)

Code

Python

from typing import List


# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children


class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        if not root:
            return []
        
        stack, ans = [root], []
        while stack:
            item = stack.pop()
            ans.append(item.val)
            for i in range(len(item.children) - 1, -1, -1):
                stack.append(item.children[i])
        return ans

以上是关于LeetCode Algorithm 589. N 叉树的前序遍历的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 589. N叉树的前序遍历(N-ary Tree Preorder Traversal)

LeetCode 589. N-ary Tree Preorder Traversal

LeetCode-589. N叉树的前序遍历

leetcode589. N-ary Tree Preorder Traversal

[LeetCode&Python] Problem 589. N-ary Tree Preorder Traversal

LeetCode 589 N叉树前序遍历[DFS] HERODING的LeetCode之路