列表

详情


590. N 叉树的后序遍历

给定一个 n 叉树的根节点 root ,返回 其节点值的 后序遍历

n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。

 

示例 1:

输入:root = [1,null,3,2,4,null,5,6]
输出:[5,6,3,2,4,1]

示例 2:

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[2,6,14,11,7,3,12,8,4,13,9,10,5,1]

 

提示:

 

进阶:递归法很简单,你可以使用迭代法完成此题吗?

相似题目

二叉树的后序遍历

N 叉树的层序遍历

N 叉树的前序遍历

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: vector<int> postorder(Node* root) { } };

golang 解法, 执行用时: 0 ms, 内存消耗: 3.8 MB, 提交时间: 2024-02-19 10:17:05

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */

func postorder(root *Node) (ans []int) {
    var dfs func(node *Node)
    dfs = func(node *Node) {
        if node != nil {
            for _, child := range node.Children {
                dfs(child)
            }
            ans = append(ans, node.Val)
        }
    }
    dfs(root)
    return
}

python3 解法, 执行用时: 55 ms, 内存消耗: 18.1 MB, 提交时间: 2024-02-19 10:16:43

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        stack, ans = [root], []
        while stack:
            if (obj := stack.pop()) is not None:
                if type(obj) == Node:
                    stack += [obj.val] + obj.children[::-1]
                else:
                    ans.append(obj)
        return ans

python3 解法, 执行用时: 46 ms, 内存消耗: 18.1 MB, 提交时间: 2024-02-19 10:15:43

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        result = []
        def post_order(root):
            if root:
                for node in root.children:
                    post_order(node)
                result.append(root.val)
        post_order(root)
        return result

golang 解法, 执行用时: 0 ms, 内存消耗: 3.9 MB, 提交时间: 2021-06-17 10:44:35

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Children []*Node
 * }
 */

func postorder(root *Node) []int {
    var res = []int{}
    if root == nil{
        return res
    }
	var st = []*Node{root}
    for len(st) > 0 {
        x := st[len(st)-1]
        st = st[:len(st)-1]
        if x != nil {
            res = append(res, x.Val)
            st = append(st, x.Children...)
        }

    }
    n := len(res)
    for i := 0; i < n/2; i++ {
        res[i], res[n-1-i] = res[n-1-i], res[i]
    }
    return res
}

上一题