Commit f37463f2 authored by 李沛勳's avatar 李沛勳
Browse files

BTN complete

parent 9338b477
#!/usr/bin/env python3
# *-* coding:utf-8 *-*
if __name__ == "__main__":
pass
# if __name__ == "__main__":
# pass
class BinTreeNode :
def __init__(self, value = None):
self.value = value
self.left = None #smaller than node
self.right = None #greater than node
class BinTree :
def __init__(self):
self.root = None
def insert(self,value): #root -> true/false
if self.root == None:
self.root = BinTreeNode(value)
else:
self.search(value,self.root)
def search(self,value,cur_node):
if value < cur_node.value:
if cur_node.left == None:
cur_node.left = BinTreeNode(value)
else:
self.search(value,cur_node.left)
elif value > cur_node.value:
if cur_node.right == None:
cur_node.right = BinTreeNode(value)
else:
self.search(value,cur_node.right)
else:
print("This value has existed")
def print_tree(self):
if self.root!=None:
self._print_tree(self.root)
def _print_tree(self,cur_node):
if cur_node!=None:
self._print_tree(cur_node.left)
print(str(cur_node.value))
self._print_tree(cur_node.right)
def fill_tree(tree, num_elems=10, max_int=50):
from random import randint
for _ in range(num_elems): #10 value
cur_elem = randint(0, max_int) #random value (0~50)
tree.insert(cur_elem)
return tree
tree = BinTree()
tree = fill_tree(tree)
tree.print_tree()
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment