Created
October 23, 2020 18:48
-
-
Save ibrahimsha23/1c91cdb2df623a52d2cb0f9b7878bf93 to your computer and use it in GitHub Desktop.
BInary Tree - Level Up ordering
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
class Node: | |
def __init__(self, data): | |
self.left, self.right = None, None | |
self.data = data | |
self.children = 0 | |
def ___print___(self): | |
print("Node--data is {}, left pointer is {} and right pointer is {} ".format( | |
self.data, | |
self.left, | |
self.right | |
)) | |
def print_tree(node, level=0): | |
if node != None: | |
printTree(node.left, level + 1) | |
print(' ' * 4 * level + '->', node.data) | |
printTree(node.right, level + 1) | |
class BinaryTree: | |
def __init__(self): | |
self.root = None | |
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
from binary_tree.base import Node, BinaryTree, print_tree | |
class LevelUpOrder(BinaryTree): | |
def tree_order(self, arr, n, i, root): | |
if i < n: | |
if root is None: | |
root = Node(arr[i]) | |
if root.left is None: | |
root.left = self.tree_order(arr, n, i*2 + 1, root.left) | |
if root.right is None: | |
root.right = self.tree_order(arr, n, i*2 + 2, root.right) | |
return root | |
array = list(range(25)) | |
luo = LevelUpOrder() | |
final_tree = luo.tree_order(array, len(array), 0, None) | |
print_tree(final_tree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment