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
}