0x00 題目
給定一個 N 叉樹,傳回其節點值的
後序周遊
0x01 後序周遊
語言:
Swift
樹節點:
Node
public class Node {
public var val: Int
public var children: [Node]
public init(_ val: Int) {
self.val = val
self.children = []
}
}
func postorder(_ root: Node?) -> [Int] {
if root == nil { return []}
var arr: [Int] = []
for child in root!.children {
let result = postorder(child)
arr.append(contentsOf: result)
}
// 最後再添加根節點
arr.append(root!.val)
return arr
}
func postorder(_ root: Node?) -> [Int] {
if root == nil { return []}
var arr: [Int] = []
var queue: [Node] = [root!]
while !queue.isEmpty {
let node = queue.removeLast()
// 插入到第 1 個位置
arr.insert(node.val, at: 0)
for t in node.children {
queue.append(t)
}
}
return arr
}