Created
October 6, 2015 22:24
-
-
Save urielhdz/296cd3af503093e10f57 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 main | |
import( | |
"fmt" | |
"strconv" | |
) | |
type Node struct { | |
right *Node | |
left *Node | |
parent *Node | |
value int | |
} | |
func(self *Node) height() int{ | |
if self.parent == nil{ | |
return 1 | |
}else{ | |
return self.parent.height() + 1 | |
} | |
} | |
type Tree struct{ | |
root_node *Node | |
} | |
func (self *Tree) add(value int) { | |
if self.root_node == nil{ | |
self.root_node = &Node{value: value} | |
}else{ | |
self.recursive_add(value, self.root_node) | |
} | |
} | |
func (self *Tree) recursive_add(value int, node *Node) { | |
if value < node.value{ | |
if node.left == nil{ | |
node.left = &Node{value: value, parent: node} | |
}else{ | |
self.recursive_add(value, node.left) | |
} | |
}else{ | |
if node.right == nil{ | |
node.right = &Node{value: value, parent: node} | |
}else{ | |
self.recursive_add(value, node.right) | |
} | |
} | |
} | |
func(self *Tree) find(value int) *Node{ | |
if self.root_node != nil{ | |
return self.recursive_find(value, self.root_node) | |
}else{ | |
return nil | |
} | |
} | |
func (self Tree) print(){ | |
self.recursive_print(self.root_node) | |
} | |
func (self Tree) recursive_print(node *Node){ | |
if node != nil{ | |
fmt.Println("Valor: "+ strconv.Itoa(node.value)) | |
self.recursive_print(node.right) | |
self.recursive_print(node.left) | |
} | |
} | |
func(self *Tree) recursive_find(value int, node *Node) *Node{ | |
if node.value == value { | |
return node | |
}else if value < node.value && node.left != nil { | |
return self.recursive_find(value,node.left) | |
}else if node.right != nil{ | |
return self.recursive_find(value,node.right) | |
}else{ | |
return nil | |
} | |
} | |
func main() { | |
/* TEST */ | |
tree := Tree{} | |
tree.add(20) | |
tree.add(10) | |
tree.add(21) | |
node := tree.find(21) | |
if node != nil{ | |
fmt.Println(node.height()) | |
}else{ | |
fmt.Println("No encontrado") | |
} | |
tree.print() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment