Leetcode 589. N-ary Tree Preorder Traversal

题目链接

https://leetcode.com/problems/n-ary-tree-preorder-traversal/description/

题目描述

Given an n-ary tree, return the preorder traversal of its nodes' values.

题解

前序遍历,把当前节点的子节点依次添加到一个栈中,依次遍历就好

代码


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

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public List<Integer> preorder(Node root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) { return list; }
        Stack<Node> s = new Stack<>();
        s.add(root);
        while (!s.isEmpty()) {
            Node node = s.pop();
            list.add(node.val);
            for (int i = node.children.size() - 1; i>=0; i--) {
                s.add(node.children.get(i));
            }
        }
        return list;
    }
}

猜你喜欢

转载自www.cnblogs.com/xiagnming/p/9591559.html