【二叉树】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
}

如何做笔记:长按 -> 复制!

粘贴 都可以去掉!
在这里插入图片描述


猜你喜欢

转载自blog.csdn.net/xjh093/article/details/118226460