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

一款小巧的在线编译器

请添加图片描述

猜你喜欢

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