Skip to content

Instantly share code, notes, and snippets.

@tsonglew
Created January 20, 2020 14:55
Show Gist options
  • Save tsonglew/c0d774965cda9de3cac2078bc0b15b34 to your computer and use it in GitHub Desktop.
Save tsonglew/c0d774965cda9de3cac2078bc0b15b34 to your computer and use it in GitHub Desktop.
morris traversal go implementation
package main
import (
"fmt"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func main() {
root := &TreeNode{
Val: 1,
Left: &TreeNode{
Val: 2,
Left: &TreeNode{Val: 4},
Right: &TreeNode{Val: 5},
},
Right: &TreeNode{Val: 3},
}
inorder(root)
}
func inorder(root *TreeNode) {
cur := root
for cur != nil {
if cur.Left == nil {
fmt.Println(cur.Val)
cur = cur.Right
} else {
p := cur.Left
for p.Right != nil {
p = p.Right
}
p.Right = cur
next := cur.Left
cur.Left = nil
cur = next
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment