天天看點

【二叉樹】N 叉樹的前序周遊

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
}