Ad
Creating A Binary Search Tree Using Binary Search Tree Class Implementation
I have defined the BinarySearchTree
class below:
class BinarySearchTree:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert(self, new_data):
if new_data == self.data:
return
elif new_data < self.data:
if self.left == None:
self.left = BinarySearchTree(new_data)
else:
self.left.insert(new_data)
else:
if self.right == None:
self.right = BinarySearchTree(new_data)
else:
self.right.insert(new_data)
def search(self, find_data):
if self.data == find_data:
return True
elif find_data < self.data and self.left != None:
return self.left.search(find_data)
elif find_data > self.data and self.right != None:
return self.right.search(find_data)
else:
return False
def get_data(self):
return self.data
def set_data(self, new_data):
self.data = new_data
def get_left(self):
return self.left
def get_right(self):
return self.right
Using this class implementation now I need to create a binary tree as shown in the vertical representation:
>>> bst = create_bst()
print_tree(bst, 0)
27
(L) 14
(L) 10
(R) 19
(R) 35
(L) 31
(R) 42
With my code here:
def create_bst():
root = BinarySearchTree(27)
root.insert(14)
root.insert(10)
root.get_left().insert(19)
root.get_left().insert(35)
root.get_left().get_left().insert(31)
root.get_left().get_right().insert(42)
return root
This is the representation I'm getting:
27
(L) 14
(L) 10
(R) 31
(R) 19
(R) 35
(R) 42
Ad
Answer
It seems to be working fine so far. Just put all the elements directly into root
without using get_left
, get_right
(since you are inserting them into the wrong node).
def create_bst():
root = BinarySearchTree(27)
root.insert(14)
root.insert(10)
root.insert(19)
root.insert(35)
root.insert(31)
root.insert(42)
return root
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad