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 preorder(_ root: Node?) -> [Int] {
if root == nil { return []}
var arr: [Int] = []
arr.append(root!.val)
for child in root!.children {
let result = preorder(child)
arr.append(contentsOf: result)
}
return arr
}
迭代遍历:
func preorder(_ root: Node?) -> [Int] {
if root == nil { return []}
var arr: [Int] = []
var queue: [Node] = [root!]
while !queue.isEmpty {
let node = queue.removeLast()
arr.append(node.val)
var children = node.children
while !children.isEmpty {
let node = children.removeLast()
queue.append(node)
}
}
return arr
}
0x02 我的小作品
欢迎体验我的作品之一:小五笔 86 版
五笔学习好帮手~
App Store 搜索即可~