|
| 1 | +## 589. N-ary Tree Preorder Traversal |
| 2 | + |
| 3 | +### Question |
| 4 | +Given an n-ary tree, return the preorder traversal of its nodes' values. |
| 5 | + |
| 6 | +For example, given a 3-ary tree: |
| 7 | +Return its preorder traversal as: [1,3,5,6,2,4]. |
| 8 | + |
| 9 | +Note: |
| 10 | +* Recursive solution is trivial, could you do it iteratively? |
| 11 | + |
| 12 | +### Solution: |
| 13 | +* Method 1: dfs |
| 14 | + ```Java |
| 15 | + /* |
| 16 | + // Definition for a Node. |
| 17 | + class Node { |
| 18 | + public int val; |
| 19 | + public List<Node> children; |
| 20 | +
|
| 21 | + public Node() {} |
| 22 | +
|
| 23 | + public Node(int _val,List<Node> _children) { |
| 24 | + val = _val; |
| 25 | + children = _children; |
| 26 | + } |
| 27 | + }; |
| 28 | + */ |
| 29 | + class Solution { |
| 30 | + private List<Integer> result; |
| 31 | + public List<Integer> preorder(Node root) { |
| 32 | + this.result = new ArrayList<>(); |
| 33 | + if(root == null) return result; |
| 34 | + dfs(root); |
| 35 | + return result; |
| 36 | + } |
| 37 | + private void dfs(Node node){ |
| 38 | + if(node == null) return; |
| 39 | + result.add(node.val); |
| 40 | + for(int i = 0; i < node.children.size(); i++){ |
| 41 | + dfs(node.children.get(i)); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + ``` |
| 46 | + |
| 47 | +* Method 2: Iteration |
| 48 | + * We need to use stack to implement this question. |
| 49 | + * For example: [1,3,5,6,2,4] |
| 50 | + * step 1: we push 1 to stack, stack: [1] |
| 51 | + * step 2: push its child to stack in reverse order. stack: [3, 2, 4] |
| 52 | + * step 3: take the first element from stack, and save all its children into stack using step 2, stack: [5, 6, 2, 4] |
| 53 | + ```Java |
| 54 | + /* |
| 55 | + // Definition for a Node. |
| 56 | + class Node { |
| 57 | + public int val; |
| 58 | + public List<Node> children; |
| 59 | +
|
| 60 | + public Node() {} |
| 61 | +
|
| 62 | + public Node(int _val,List<Node> _children) { |
| 63 | + val = _val; |
| 64 | + children = _children; |
| 65 | + } |
| 66 | + }; |
| 67 | + */ |
| 68 | + class Solution { |
| 69 | + public List<Integer> preorder(Node root) { |
| 70 | + List<Integer> result = new ArrayList<>(); |
| 71 | + if(root == null) return result; |
| 72 | + Stack<Node> stack = new Stack<>(); |
| 73 | + stack.push(root); |
| 74 | + while(!stack.isEmpty()){ |
| 75 | + Node node = stack.pop(); |
| 76 | + result.add(node.val); |
| 77 | + for(int i = node.children.size() - 1; i >= 0; i--){ |
| 78 | + stack.push(node.children.get(i)); |
| 79 | + } |
| 80 | + } |
| 81 | + return result; |
| 82 | + } |
| 83 | + } |
| 84 | + ``` |
| 85 | + |
| 86 | +### Reference |
| 87 | +1. [Leetcode 589. N-ary Tree Preorder Traversal](https://www.cnblogs.com/xiagnming/p/9591559.html) |
0 commit comments