|
| 1 | +//LeetCode 590. N-ary Tree Postorder Traversal |
| 2 | +//Question - https://leetcode.com/problems/n-ary-tree-postorder-traversal/ |
| 3 | + |
| 4 | +/* |
| 5 | +// Definition for a Node. |
| 6 | +class Node { |
| 7 | + public int val; |
| 8 | + public List<Node> children; |
| 9 | +
|
| 10 | + public Node() {} |
| 11 | +
|
| 12 | + public Node(int _val) { |
| 13 | + val = _val; |
| 14 | + } |
| 15 | +
|
| 16 | + public Node(int _val, List<Node> _children) { |
| 17 | + val = _val; |
| 18 | + children = _children; |
| 19 | + } |
| 20 | +}; |
| 21 | +*/ |
| 22 | + |
| 23 | +class Solution { |
| 24 | + |
| 25 | + List<Integer> result = new ArrayList<>(); |
| 26 | + |
| 27 | + public List<Integer> postorderIterative(Node root) { |
| 28 | + List<Integer> res = new ArrayList<>(); |
| 29 | + if(root == null) return res; |
| 30 | + |
| 31 | + /* |
| 32 | + Observation - |
| 33 | + Pre-order = root, left, right |
| 34 | + Post-order = left, right, root |
| 35 | + |
| 36 | + Reversing pre-order, we get (right, left, root). This means for each node, |
| 37 | + we start from the rightmost child and move to the leftmost child and keep |
| 38 | + recording the values. |
| 39 | + |
| 40 | + Reversing the recorded values would yield the post-order traversal. |
| 41 | + */ |
| 42 | + |
| 43 | + Stack<Node> stk = new Stack<>(); |
| 44 | + Stack<Integer> order = new Stack<>(); |
| 45 | + |
| 46 | + stk.push(root); |
| 47 | + while(!stk.isEmpty()){ |
| 48 | + Node node = stk.pop(); |
| 49 | + |
| 50 | + //recoding the values of traversal |
| 51 | + order.push(node.val); |
| 52 | + |
| 53 | + //iterating from leftmost child. But we are using stack, the rightmost child |
| 54 | + //would be on the top. |
| 55 | + for(Node child : node.children){ |
| 56 | + stk.push(child); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + //reversing the recorded values |
| 61 | + while(!order.isEmpty()){ |
| 62 | + res.add(order.pop()); |
| 63 | + } |
| 64 | + |
| 65 | + return res; |
| 66 | + } |
| 67 | + |
| 68 | + public List<Integer> postorderRecursive(Node root) { |
| 69 | + if(root == null) return result; |
| 70 | + |
| 71 | + List<Node> children = root.children; |
| 72 | + for(Node child : children){ |
| 73 | + postorderRecursive(child); |
| 74 | + } |
| 75 | + |
| 76 | + result.add(root.val); |
| 77 | + return result; |
| 78 | + } |
| 79 | +} |
0 commit comments