递归版
class Solution{
List<Integer> res = new ArrayList<Integer>();
public List<Integer> preorder(Node root){
if(root == null)
{
return res;
}
res.add(root);
//冒号左边是root所有孩子,不断的去遍历
for(Node child:root.children)
{
preorder(child);
}
return res;
}
}
非递归:
1.二叉树的非递归前序遍历,根节点压入栈中。
2.然后将栈顶节点弹出,把弹出的那个节点的左右孩子按照从右到左的顺序压入栈中。
3.推广到n叉树,把根节点放入栈中,弹出栈顶元素,再把栈顶元素的孩子们按照从右到左的顺序压入栈中
class Solution{
public List<Integer> preorder(Node root){
List<Integer> res = new ArrayList<Integer>();
Stack<Node> stack = new Stack<Node>();
if(root == null)
{
return res;
}
stack.push(root);
while(!stack.isEmpty())
{
Node node = stack.pop();
res.add(node.val);
for(int i=node.children.size()-1;i>=0;i--)
{
stack.push(ndoe.childrem.get(i));
}
}
return res;
}
}