Created
April 9, 2019 16:53
-
-
Save GypsyDangerous/a52c20f4d605936f325c07755222f83a to your computer and use it in GitHub Desktop.
BST created by davidsnyder1 - https://repl.it/@davidsnyder1/BST
This file contains hidden or 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
import random | |
class Node: | |
def __init__(self,key): | |
self.left = None | |
self.right = None | |
self.val = key | |
def insert(self, node): | |
if self.val < node.val: | |
if self.right is None: | |
self.right = node | |
else: | |
self.right.insert(node) | |
else: | |
if self.left is None: | |
self.left = node | |
else: | |
self.left.insert(node) | |
def insertval(self, val): | |
if self.val < val: | |
if self.right is None: | |
self.right = Node(val) | |
else: | |
self.right.insertval(val) | |
else: | |
if self.left is None: | |
self.left = Node(val) | |
else: | |
self.left.insertval(val) | |
def fromArray(self, arr): | |
for i in arr: | |
self.insertval(i) | |
# A utility function to do inorder tree traversal | |
def inorder(self): | |
if self.left: | |
self.left.inorder() | |
print(self.val) | |
if self.right: | |
self.right.inorder() | |
def toArray(self, arr=list): | |
if self.left: | |
self.left.toArray(arr) | |
arr.append(self.val) | |
if self.right: | |
self.right.toArray(arr) | |
return arr | |
unsorted = [int(random.random()*100) for i in range(10)] | |
print(unsorted) | |
r = Node(unsorted[0]) | |
r.fromArray(unsorted[1:]) | |
sort = [] | |
sort = r.toArray(sort) | |
print(sort) | |
# r.inorder() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment