[算法]N 叉树的后序遍历

60 阅读1分钟

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
}

0x02 我的小作品

欢迎体验我的作品之一:小五笔
五笔学习好帮手~
App Store 搜索即可~