跳至主要內容

590. N叉树的后续遍历

专题leetcodeleetcode小于 1 分钟

590. N叉树的后续遍历

题目

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

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

https://leetcode.cn/problems/n-ary-tree-postorder-traversal/open in new window

解法

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
    public List<Integer> postorder(Node root) {
        List<Integer> res = new LinkedList<>();
        process(root, res);
        return res;
    }

    private void process(Node root, List<Integer> res) {
        if (root == null) {
            return;
        }

        if (root.children != null){
            for (Node child : root.children) {
                process(child, res);
            }
        }

        res.add(root.val);
    }
}

版权申明

本站点所有内容,版权均归https://wenchao.renopen in new window所有,除非明确授权,否则禁止一切形式的转载协议

打赏

微信 支付宝

上次编辑于:
打赏
给作者赏一杯咖啡吧
您的支持将是我继续更新下去的动力
微信微信
支付宝支付宝