|
| 1 | +/* https://leetcode.com/problems/n-ary-tree-postorder-traversal/ |
| 2 | +Given the root of an n-ary tree, return the postorder traversal of its nodes' values. |
| 3 | +
|
| 4 | +Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) |
| 5 | +
|
| 6 | +Example 1: |
| 7 | +
|
| 8 | +Input: root = [1,null,3,2,4,null,5,6] |
| 9 | +Output: [5,6,3,2,4,1] |
| 10 | +Example 2: |
| 11 | +
|
| 12 | +Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] |
| 13 | +Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1] |
| 14 | +
|
| 15 | +Constraints: |
| 16 | +
|
| 17 | +The number of nodes in the tree is in the range [0, 10^4]. |
| 18 | +0 <= Node.val <= 10^4 |
| 19 | +The height of the n-ary tree is less than or equal to 1000. |
| 20 | +*/ |
| 21 | + |
| 22 | +package ltree |
| 23 | + |
| 24 | +type Node struct { |
| 25 | + Val int |
| 26 | + Children []*Node |
| 27 | +} |
| 28 | + |
| 29 | +func postorder(root *Node) []int { |
| 30 | + // var helper func(root *Node, ans *[]int) |
| 31 | + // helper = func(root *Node, ans *[]int) { |
| 32 | + // if root == nil { |
| 33 | + // return |
| 34 | + // } |
| 35 | + // for _, child := range root.Children { |
| 36 | + // helper(child, ans) |
| 37 | + // } |
| 38 | + // *ans = append(*ans, root.Val) |
| 39 | + // } |
| 40 | + |
| 41 | + // ans := []int{} |
| 42 | + // helper(root, &ans) |
| 43 | + // return ans |
| 44 | + |
| 45 | + ans := []int{} |
| 46 | + stack := []*Node{root} |
| 47 | + for len(stack) != 0 { |
| 48 | + cur := stack[len(stack)-1] |
| 49 | + ans = append(ans, cur.Val) |
| 50 | + stack = stack[:len(stack)-1] |
| 51 | + for _, child := range cur.Children { |
| 52 | + stack = append(stack, child) |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 { |
| 57 | + ans[i], ans[j] = ans[j], ans[i] |
| 58 | + } |
| 59 | + |
| 60 | + return ans |
| 61 | +} |
0 commit comments