leetcode589. N叉树的前序遍历
给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树 :

返回其前序遍历: [1,3,5,6,2,4]。
递归法
1 2 3 4 5 6 7 8 9 10 11
| class Solution { public ArrayList<Integer>list=new ArrayList<>(); public List<Integer> preorder(Node root) { if(root==null)return list; list.add(root.val); for(Node n:root.children){ preorder(n); } return list; } }
|
非递归法
非递归法肯定是用栈了,往这上面靠。发现有一种方式可行:把儿子节点从右到左依次入栈,这样每次出栈的时候就符合前序遍历。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public List<Integer> preorder(Node root) { ArrayList<Integer>list=new ArrayList<>(); if(root==null)return list; Stack<Node>stack=new Stack<>(); stack.push(root); while(!stack.isEmpty()){ Node pop=stack.pop(); list.add(pop.val); for(int i=pop.children.size()-1;i>=0;i--){ stack.push(pop.children.get(i)); } } return list; }
|
leetcode 40/100