package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {
// If right child exists, go to leftmost node in right subtree
if p.Right != nil {
curr := p.Right
for curr.Left != nil {
curr = curr.Left // advance to leftmost node
}
return curr
}
// Otherwise, start from root and track successor
var successor *TreeNode
curr := root
for curr != nil {
if p.Val < curr.Val {
successor = curr // update successor
curr = curr.Left // move left to find smaller successor
} else {
curr = curr.Right // move right to find p
}
}
return successor
}
func main() {
// Build BST
root := &TreeNode{5, nil, nil}
root.Left = &TreeNode{3, nil, nil}
root.Right = &TreeNode{7, nil, nil}
root.Left.Left = &TreeNode{2, nil, nil}
root.Left.Right = &TreeNode{4, nil, nil}
root.Right.Right = &TreeNode{8, nil, nil}
p := root.Left.Right // node with value 4
succ := inorderSuccessor(root, p)
if succ != nil {
fmt.Printf("Successor of %d is %d\n", p.Val, succ.Val)
} else {
fmt.Printf("No successor for %d\n", p.Val)
}
}
Check if node has right subtree to find successor there
Traverse to leftmost node in right subtree for smallest greater value
Initialize variable to track potential successor
Traverse tree from root to find successor by comparing values
If current node value greater than p, update successor and go left
else { curr = curr.Right }
If current node value less or equal, go right to find p