Given an n-ary tree, return the preorder traversal of its nodes' values.
For example, given a 3-ary
tree:
Return its preorder traversal as: [1,3,5,6,2,4]
.
Note:
Recursive solution is trivial, could you do it iteratively?
解题思路一:递归实现
/*
// 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> res = new ArrayList<Integer>();
preOrder(res,root);
return res;
}
public void preOrder(List<Integer> res, Node root){
if(root==null) return;
res.add(root.val);
for(int i=0;i<root.children.size();i++)
preOrder(res,root.children.get(i));
}
}
解题思路二:非递归遍历。前序的非递归遍历容易实现,即先访问根,再将子结点从右往左压栈。
/*
// 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> res = new ArrayList<Integer>();
Stack<Node> st = new Stack<Node>();
st.push(root);
Node p = null;
while(st.empty()==false){
p = st.pop();
if(p!=null){
res.add(p.val);
for(int i=p.children.size()-1;i>=0;i--){
st.push(p.children.get(i));
}
}
}
return res;
}
}