Given an n-ary tree, return the preorder traversal of its nodes' values.java
For example, given a 3-ary
tree:node
Return its preorder traversal as: [1,3,5,6,2,4]
.spa
Note:code
Recursive solution is trivial, could you do it iteratively?blog
題目地址遞歸
若是用遞歸來解題的話,仍是很是簡單的。若是要用迭代來解題,無非就是用棧來實現。要注意的一點是,須要一個額外的棧來把壓棧的順序倒一下序。leetcode
遞歸代碼:rem
/* // 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 { private List<Integer> result = new ArrayList<>(); public List<Integer> preorder(Node root) { if(root==null){ return result; } result.add(root.val); for(Node node:root.children){ preorder(node); } return result; } }
迭代代碼:get
/* // 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 { private List<Integer> result = new ArrayList<>(); private Stack<Node> stack = new Stack<>(); private Stack<Node> stack_temp = new Stack(); public List<Integer> preorder(Node root) { if(root==null){ return result; } stack.push(root); while(!stack.empty()){ Node theNode = stack.pop(); result.add(theNode.val); for(Node node:theNode.children){ stack_temp.push(node); } while(!stack_temp.empty()){ stack.push(stack_temp.pop()); } } return result; } }