题目链接
题目描述
Given an n-ary tree, return the preorder traversal of its nodes' values.
题解
前序遍历,把当前节点的子节点依次添加到一个栈中,依次遍历就好
代码
/*// Definition for a Node.class Node { public int val; public Listchildren; public Node() {} public Node(int _val,List _children) { val = _val; children = _children; }};*/class Solution { public List preorder(Node root) { List list = new ArrayList<>(); if (root == null) { return list; } Stack 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; }}