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
}
如何做笔记:长按 -> 复制!
连 粘贴
都可以去掉!