1.题目
2.题解
2.1递归
2.2迭代
给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树
:
返回其前序遍历: [1,3,5,6,2,4]
。
说明: 递归法很简单,你可以使用迭代法完成此题吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
public class Solution589 {
@Test
public void test589() {
Node n = new Node(3, Arrays.asList(new Node(5), new Node(6)));
Node root = new Node(1,Arrays.asList(n,new Node(2),new Node(4)));
System.out.println(preorder(root));
}
List list = new ArrayList<>();
public List preorder(Node root) {
pre(root);
return list;
}
public void pre(Node root) {
if (root == null) {
return;
}
list.add(root.val);
if (root.children!=null){
for (Node n : root.children) {
pre(n);
}
}
}
}
public class Solution589 {
@Test
public void test589() {
Node n = new Node(3, Arrays.asList(new Node(5), new Node(6)));
Node root = new Node(1,Arrays.asList(n,new Node(2),new Node(4)));
System.out.println(preorder(root));
}
List list = new ArrayList<>();
public List preorder(Node root) {
Stack stack = new Stack<>();
if (root != null){
stack.push(root);
while (!stack.isEmpty()){
Node t = stack.pop();
list.add(t.val);
if (t.children!=null){
Collections.reverse(t.children);
stack.addAll(t.children);
}
}
}
return list;
}
}