答应你们的后序遍历迭代法来了。
思路:
先是跟前序遍历一个思路,不过是按中右左的顺序生成,再见结果集反转,便成了左右中。
// 后续遍历 迭代做法
func postorderTraversal(root *TreeNode) []int {
res := make([]int, 0)
if root == nil {
return res
}
st := list.New()
st.PushBack(root)
for st.Len() > 0 {
pop := st.Remove(st.Back()).(*TreeNode)
res = append(res, pop.Val)
if pop.Left != nil {
st.PushBack(pop.Left)
}
if pop.Right != nil {
st.PushBack(pop.Right)
}
}
for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
res[i], res[j] = res[j], res[i]
}
return res
}