Skip to content

Commit

Permalink
initial implementation of binary trees
Browse files Browse the repository at this point in the history
  • Loading branch information
nimrodshn committed Nov 5, 2019
1 parent 488d4e6 commit 6fde561
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
2 changes: 1 addition & 1 deletion binarysearch/binary_search.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package binarysearch

// BinarySearch finds an element x in a sorted arrray
// BinarySearch finds an element x in a sorted array
// it returns the index of the element x in the array or -1,
// if no such element exist.
func BinarySearch(input []int, x int) int {
Expand Down
49 changes: 49 additions & 0 deletions binarytree/binary_tree.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package binarytree

// BinaryTree is a representation of a binary tree
type BinaryTree struct {
root *Node
}

// Node represents a node in the binary tree.
type Node struct {
key int
left *Node
right *Node
}

func (b *BinaryTree) Min() *Node {
node := b.root
for node.left != nil {
node = node.left
}
return node
}

func (b *BinaryTree) Max() *Node {
node := b.root
for node.right != nil {
node = node.right
}
return node
}

// Search returns the node in the Binary Tree with a given key.
func (b *BinaryTree) Search(key int) *Node {
return search(b.root, key)
}

// A helper function for Search.
func search(x *Node ,key int) *Node {
for x != nil {
if x.key == key {
return x
}
if key < x.key {
x = x.left
} else {
x = x.right
}
}
return nil
}

0 comments on commit 6fde561

Please sign in to comment.