Created
December 5, 2019 10:06
-
-
Save vizee/3796e97488592bc08998a1cd8bde0399 to your computer and use it in GitHub Desktop.
treap
This file contains 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 treap | |
type node struct { | |
key int | |
prior int | |
left *node | |
right *node | |
} | |
func zig(p *node) *node { | |
right := p.right | |
p.right = right.left | |
right.left = p | |
return right | |
} | |
func zag(p *node) *node { | |
left := p.left | |
p.left = left.right | |
left.right = p | |
return left | |
} | |
func insert(p *node, key int, prior int) *node { | |
if p == nil { | |
p = &node{ | |
key: key, | |
prior: prior, | |
} | |
} else if key < p.key { | |
p.left = insert(p.left, key, prior) | |
if p.left.prior < p.prior { | |
p = zag(p) | |
} | |
} else { | |
p.right = insert(p.right, key, prior) | |
if p.right.prior < p.prior { | |
p = zig(p) | |
} | |
} | |
return p | |
} | |
func remove(p *node, key int) *node { | |
if p == nil { | |
return nil | |
} | |
if key < p.key { | |
p.left = remove(p.left, key) | |
} else if key > p.key { | |
p.right = remove(p.right, key) | |
} else if p.left == nil { | |
p = p.right | |
} else if p.right == nil { | |
p = p.left | |
} else if p.left.prior < p.right.prior { | |
p = zag(p) | |
p.right = remove(p.right, key) | |
} else { | |
p = zig(p) | |
p.left = remove(p.left, key) | |
} | |
return p | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment