Create Binary Tree from a List of Values in Python
Run and Try: https://repl.it/@VinitKhandelwal/create-binary-tree
Root's left Value: 10
Root's right Value: 30
Run and Try: https://repl.it/@VinitKhandelwal/create-binary-tree
class Node():
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class BinaryTree():
def __init__(self, mylist):
self.mylist = mylist
self.root=Node(None)
for value in self.mylist:
self.curr=self.root
self._add(value)
def _add(self, value):
if self.curr.value == None:
self.curr.value = value
else:
if self.curr.value > value:
if self.curr.left == None:
self.curr.left = Node(value)
else:
self.curr = self.curr.left
self._add(value)
else:
if self.curr.right == None:
self.curr.right = Node(value)
else:
self.curr = self.curr.right
self._add(value)
obj = BinaryTree([20,10,30])
print("Root Value: {}".format(obj.root.value))
print("Root's left Value: {}".format(obj.root.left.value))
print("Root's right Value: {}".format(obj.root.right.value))
Output
Root Value: 20Root's left Value: 10
Root's right Value: 30
Comments
Post a Comment