Skip to content

Instantly share code, notes, and snippets.

@alldroll
Last active July 2, 2020 08:33
Show Gist options
  • Select an option

  • Save alldroll/e973d38137b52199d18c8c416b42a7a6 to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/e973d38137b52199d18c8c416b42a7a6 to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func inorderSuccessor(root *TreeNode, p *TreeNode) *TreeNode {
if root == nil || p == nil {
return nil
}
return inorder(root, p)
}
func inorder(root, p *TreeNode) *TreeNode {
stack := []*TreeNode{}
target := (1 << 31) - 1
for root != nil || len(stack) > 0 {
for root != nil {
stack = append(stack, root)
root = root.Left
}
root = stack[len(stack) - 1]
stack = stack[:len(stack) - 1]
if target == p.Val {
return root
}
target = root.Val
root = root.Right
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment