Leetcode 589. N-ary Tree Preorder Traversal
DFS,两种实现方式,递归和栈.
""" # 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]: if not root: return [] stack,ans=[root],[] while stack: node=stack.pop() ans.append(node.val) if node.children: stack.extend(reversed(node.children)) return ans
""" # 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]: if not root: return [] ans=[root.val] for c in root.children: ans+=self.preorder(c) return ans