dave on Nostr: // 前序遍历 func PreorderTraversal(root *TreeNode) []int { res := []int{} ...
// 前序遍历
func PreorderTraversal(root *TreeNode) []int {
res := []int{}
rootNode := root
stack := []*TreeNode{}
for rootNode != nil || len(stack) > 0 {
for rootNode != nil {
res = append(res, rootNode.Val)
stack = append(stack, rootNode)
rootNode = rootNode.Left
}
if len(stack) > 0 {
rootNode = stack[len(stack)-1]
stack = stack[:len(stack)-1]
rootNode = rootNode.Right
}
}
return res
}
// 中序遍历
func InorderTraversal(root *TreeNode) []int {
res := []int{}
stack := []*TreeNode{}
rootNode := root
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)
res = append([]int{rootNode.Val}, res...)
rootNode = rootNode.Right
}
if len(stack) > 0 {
rootNode = stack[len(stack)-1]
stack = stack[:len(
func PreorderTraversal(root *TreeNode) []int {
res := []int{}
rootNode := root
stack := []*TreeNode{}
for rootNode != nil || len(stack) > 0 {
for rootNode != nil {
res = append(res, rootNode.Val)
stack = append(stack, rootNode)
rootNode = rootNode.Left
}
if len(stack) > 0 {
rootNode = stack[len(stack)-1]
stack = stack[:len(stack)-1]
rootNode = rootNode.Right
}
}
return res
}
// 中序遍历
func InorderTraversal(root *TreeNode) []int {
res := []int{}
stack := []*TreeNode{}
rootNode := root
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)
res = append([]int{rootNode.Val}, res...)
rootNode = rootNode.Right
}
if len(stack) > 0 {
rootNode = stack[len(stack)-1]
stack = stack[:len(