Skip to content

Commit ff6e945

Browse files
authored
Create N-ary Tree Preorder Traversal.java
1 parent 4f4d074 commit ff6e945

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// 589. N-ary Tree Preorder Traversal
2+
class Solution {
3+
public List<Integer> preorder(Node root) {
4+
if (root == null)
5+
return new ArrayList<>();
6+
7+
List<Integer> ans = new ArrayList<>();
8+
Deque<Node> stack = new ArrayDeque<>();
9+
stack.push(root);
10+
11+
while (!stack.isEmpty()) {
12+
root = stack.pop();
13+
ans.add(root.val);
14+
for (int i = root.children.size() - 1; i >= 0; --i)
15+
stack.push(root.children.get(i));
16+
}
17+
18+
return ans;
19+
}
20+
}

0 commit comments

Comments
 (0)