dave on Nostr: // 后序遍历 func PostorderTraversal(root *TreeNode) []int { res := []int{} ...
// 后序遍历
func PostorderTraversal(root *TreeNode) []int {
res := []int{}
rootNode := root
stack := []*TreeNode{}
for rootNode != nil || len(stack) > 0 {
for rootNode != nil {
stack = append(stack, rootNode)
rootNode = rootNode.Left
}
if len(stack) > 0 {
rootNode = stack[len(stack)-1]
stack = stack[:len(stack)-1]
res = append(res, rootNode.Val)
rootNode = rootNode.Right
}
}
return res
}
func PostorderTraversal(root *TreeNode) []int {
res := []int{}
rootNode := root
stack := []*TreeNode{}
for rootNode != nil || len(stack) > 0 {
for rootNode != nil {
stack = append(stack, rootNode)
rootNode = rootNode.Left
}
if len(stack) > 0 {
rootNode = stack[len(stack)-1]
stack = stack[:len(stack)-1]
res = append(res, rootNode.Val)
rootNode = rootNode.Right
}
}
return res
}