Beispiel #1
0
import sys
import itertools
from tree import binary_tree
from collections import deque

#input params
input_list = [-3, -2, 1, 9, 5, -1, 11];
#input_list = [2, 1, 3];
tree = binary_tree(input_list);

print("LEVELS OF OUR TREE:");
tree.print_tree();
print("");

'''
SOLUTION: note that -
*everything on the same level can be added in ANY ORDER
*every level should be added in ASCENDING ORDER
'''

#make a list of nodes on same level using BFS
node_list = deque([tree.root, None]);
counter = tree.give_height()+1;

final_list = [];
print_list = [];

while(counter and tree.root and node_list):
    element = node_list.popleft();
    if (not element):
        final_list.append(print_list);
Beispiel #2
0
import sys
from rand_node import random_travel
from tree import binary_tree
from random import randint

#input params
input_list = [-3, -2, 1, 9, 5, -1, 11]
tree = binary_tree(input_list)

#NOTE: we find a random 'node' to make a sub-tree from OR we generate a random tree
rand_subtree = None
rand_tree = None
if (randint(0, 1)):
    rand_subtree = random_travel(tree)
else:
    rand_input_list = [
        randint(-10, 10) for index in range(len(input_list) // 2)
    ]
    rand_tree = binary_tree(rand_input_list)
    rand_subtree = random_travel(rand_tree)

#SOLUTION STARTS HERE


#we convert input tree to a 'string' using pre-order traversal that keeps track of parent-child relationship
#NOTE: this DOES NOT work with in-order traversal due to it simply sorting the tree contents
def pre_order(input_node, final_list):
    #handle special case
    if (not input_node):
        final_list.append(None)
    else:
Beispiel #3
0
import sys
from tree import binary_tree

input_list = [-3, -2, -1, 1, 5, 9, 11];
tree = binary_tree();

#make a recursive routine that vists the array elements in a 'binary search tree'-like method, and adds them to the actual tree...
#...while it does so
def minimal(array, range_arr, tree):
    #add the median to the tree
    median = sum(range_arr)//2;
    tree.extend_tree([array[median]]);
    
    #recursively add the array to the left and the right of the median
    left_range = [range_arr[0], median-1];
    if (left_range[1] >= left_range[0]):
        minimal(array, left_range, tree);
    right_range = [median+1, range_arr[1]];
    if (right_range[0] <= right_range[1]):
        minimal(array, right_range, tree);

#call the recursive routine    
if (not input_list):
    print("ERROR: no array");
    exit(-1);

minimal(input_list, [0, len(input_list)-1], tree);

#print the tree
print("LAYERS OF PRODUCED TREE:");
tree.print_tree();