-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
initial implementation of binary trees
- Loading branch information
Showing
2 changed files
with
50 additions
and
1 deletion.
There are no files selected for viewing
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
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
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 | ||
} |