Skip to content

Commit fb846bf

Browse files
committed
add 589. N-ary Tree Preorder Traversal
1 parent b7cf7cb commit fb846bf

File tree

4 files changed

+69
-0
lines changed

4 files changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
3+
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
4+
5+
Example 1:
6+
Input: root = [1,null,3,2,4,null,5,6]
7+
Output: [1,3,5,6,2,4]
8+
9+
Example 2:
10+
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
11+
Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
12+
*/
13+
14+
public class Node {
15+
public var val: Int
16+
public var children: [Node]
17+
public init(_ val: Int) {
18+
self.val = val
19+
self.children = []
20+
}
21+
}
22+
23+
// TC: O(n), where N is the number of nodes
24+
// SC: O(n), we could keep up to the entire tree
25+
// Recursive
26+
class Solution {
27+
func preorder(_ root: Node?) -> [Int] {
28+
var result = [Int]()
29+
30+
func traverse(_ node: Node?) {
31+
guard let node = node else { return }
32+
result.append(node.val)
33+
for child in node.children {
34+
traverse(child)
35+
}
36+
}
37+
38+
traverse(root)
39+
return result
40+
}
41+
}
42+
43+
// Iteratively
44+
class Solution1 {
45+
func preorder(_ root: Node?) -> [Int] {
46+
guard let root = root else { return [] }
47+
var result = [Int]()
48+
var stack = [root]
49+
50+
while !stack.isEmpty {
51+
let node = stack.removeLast()
52+
result.append(node.val)
53+
stack.append(contentsOf: node.children.reversed())
54+
}
55+
56+
return result
57+
}
58+
}
59+
60+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='7.0' target-platform='ios' swift-version='6' buildActiveScheme='true' importAppTypes='true'/>

Explore/N-ary Tree/589. N-ary Tree Preorder Traversal/MyPlayground.playground/playground.xcworkspace/contents.xcworkspacedata

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)