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