1. General Binary Tree
General Binary Tree¶
- creation of a tree using a list
https://stackoverflow.com/questions/44895195/creating-a-binary-tree-through-a-loop
values = [1,2,3,4,5,6,7]
1
2 3
4 5 6 7
In [3]:
Copied!
from utils.tree_traversal import TreeTraversal as tt
from utils.tree_traversal import TreeTraversal as tt
In [2]:
Copied!
class Node(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def buildTree(i):
if i < len(values):
return Node(
values[i], left=buildTree((i + 1) * 2 - 1), right=buildTree((i + 1) * 2)
)
values = [1, 2, 3, 4, 5, 6, 7]
tree = buildTree(0)
class Node(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def buildTree(i):
if i < len(values):
return Node(
values[i], left=buildTree((i + 1) * 2 - 1), right=buildTree((i + 1) * 2)
)
values = [1, 2, 3, 4, 5, 6, 7]
tree = buildTree(0)
In [4]:
Copied!
tt.traverse_preorder(tree)
tt.traverse_preorder(tree)
1 2 4 5 3 6 7
In [ ]:
Copied!