Created
March 6, 2023 14:11
-
-
Save vxcute/609d56e8c1b1d1b5463f86e18e2ceedb to your computer and use it in GitHub Desktop.
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 bintree | |
import "fmt" | |
type Node[T any] struct { | |
key int | |
value T | |
right *Node[T] | |
left *Node[T] | |
} | |
func NewNode[T any](n int, v T) *Node[T] { | |
return &Node[T]{key: n, value: v} | |
} | |
func (n *Node[T]) Set(k int, v T) { | |
if n == nil { | |
return | |
} | |
if k > n.key { | |
if n.right == nil { | |
n.right = NewNode(k, v) | |
} else { | |
n.right.Set(k, v) | |
} | |
} else if k < n.key { | |
if n.left == nil { | |
n.left = NewNode(k, v) | |
} else { | |
n.left.Set(k, v) | |
} | |
} | |
} | |
func (n *Node[T]) GetNode(k int) *Node[T] { | |
if n == nil || k == n.key { | |
return n | |
} | |
if k < n.key { | |
return n.left.GetNode(k) | |
} else { | |
return n.right.GetNode(k) | |
} | |
} | |
func (n *Node[T]) Get(k int) T { | |
return n.GetNode(k).value | |
} | |
func (n *Node[T]) Print() { | |
if n == nil { | |
return | |
} | |
fmt.Printf("%d -> %v\n", n.key, n.value) | |
n.left.Print() | |
n.right.Print() | |
} | |
func (n *Node[T]) Invert() { | |
if n == nil { | |
return | |
} | |
n.left.Invert() | |
n.right.Invert() | |
n.right, n.left = n.left, n.right | |
} | |
func (n *Node[T]) Min() int { | |
if n.left == nil { | |
return n.key | |
} | |
return n.left.Min() | |
} | |
func (n *Node[T]) Max() int { | |
if n.right == nil { | |
return n.key | |
} | |
return n.right.Max() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment