原题链接:https://leetcode.com/problems/n-ary-tree-preorder-traversal/
1. 题目介绍
Given an n-ary tree, return the preorder traversal of its nodes’ values.
For example, given a 3-ary tree:
给出一个n-叉树,返回先序遍历的结果。
如果是二叉树,先序遍历的顺序是:
1 根结点
2 左子树
3 右子树
如果是n叉树,那么就是先遍历根节点,然后依次遍历各个子树。
比如下面这个三叉树:
Return its preorder traversal as: [1,3,5,6,2,4].
返回的结果是:[1,3,5,6,2,4].
2. 解题思路
2.1 递归
递归的方法仍然是最容易实现的,先将根节点放入List,然后依次遍历其余的子树。
实现代码
/*
// 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> l = new ArrayList<>();
return helper(root,l);
}
public List<Integer> helper(Node root,List<Integer> l){
if(root == null){
return l;
}
l.add(root.val);
for(Node i : root.children){
helper(i,l);
}
return l;
}
}
2.2 迭代
使用堆栈辅助遍历。
每当遍历一个节点的时候,首先将根节点的val存入List中。
然后倒着将每个子树都放入堆栈中,第一个子树不要放入堆栈,用于继续遍历。
当该节点没有子树的时候,弹出栈顶存放的节点继续遍历。
实现代码
/*
// 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> l = new ArrayList<>();
Stack<Node> s = new Stack<>();
Node temp = root;
while(temp != null || s.isEmpty() != true){
if(temp != null){
l.add(temp.val);
int length = temp.children.size();
if(length == 0){
temp = null;
continue;
}
for(int i = length -1; i > 0 ; i--){
s.push(temp.children.get(i));
}
temp = temp.children.get(0);
}
else{
temp = s.pop();
}
}
return l;
}
}