1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| /** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */
func postorder(root *Node) []int { ans := []int{} if root == nil { return ans } stack := []*Node{root} set := make(map[*Node]bool) for len(stack) > 0 { node := stack[len(stack)-1] stack = stack[:len(stack)-1] n := len(node.Children) if n > 0 && !set[node] { stack = append(stack, node) set[node] = true for i := n - 1; i >= 0; i-- { stack = append(stack, node.Children[i]) } } else { ans = append(ans, node.Val) } } return ans }
|