-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathn-aryTreePreorderTraversal.py
More file actions
38 lines (33 loc) · 929 Bytes
/
n-aryTreePreorderTraversal.py
File metadata and controls
38 lines (33 loc) · 929 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/n-ary-tree-preorder-traversal/
# Author: Miao Zhang
# Date: 2021-02-23
"""
# 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]:
res = []
self.pre(root, res)
return res
def pre(self, root: 'Node', res: List[int]):
if not root: return;
res.append(root.val)
for ch in root.children:
self.pre(ch, res)
class Solution:
def preorder(self, root: 'Node') -> List[int]:
res = []
if not root: return res
stack = []
stack.append(root)
while stack:
node = stack.pop()
res.append(node.val)
stack.extend(node.children[::-1])
return res