Created
January 20, 2020 14:55
-
-
Save tsonglew/c0d774965cda9de3cac2078bc0b15b34 to your computer and use it in GitHub Desktop.
morris traversal go implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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