def createMinimalBST(array, start, end): if (end < start): return None mid = (start + end) // 2 node = Node(array[mid]) node.left = createMinimalBST(array, start, mid - 1) node.right = createMinimalBST(array, mid + 1, end) return node
def sortedArrToBST(arr,start,end): """ The inorder traverse of BFS is the same as the sorted array """ if start > end: return None if start == end: return Node(arr[start]) mid = (start + end)/2 + 1 root = Node(arr[mid]) root.left = sortedArrToBST(arr,start, mid-1) root.right = sortedArrToBST(arr, mid+1 , end) return root
def testTreeWithOneNode(): print(divider + "Executing testTreeWithOneNode()...") tree = BinaryTree() tree.insert(Node(0)) assert (tree.size == 1) assert (tree.height == 0) print("Passed" + divider)
def tree(self): chars = list(set(self.text)) occurs = {c: self.text.count(c)/len(self.text) for c in self.text} key = lambda i: occurs[i] chars = sorted(chars, key = key) nodes = [Node(label = c) for c in chars] while len(nodes) > 1: n1, n2 = nodes[0], nodes[1] del nodes[0] nodes[0] = Node(label = n1.label+n2.label, left_neigh = n1, right_neigh = n2) occurs[nodes[0].label] = occurs[n1.label] + occurs[n2.label] i = 0 while i < len(nodes) - 1 and occurs[nodes[i].label] >= occurs[nodes[i+1].label]: nodes[i], nodes[i+1] = nodes[i+1], nodes[i] i += 1 return BinaryTree(nodes[0], chars)
def testSingleInserts(loops): print(divider + "Executing testSingleInserts()...") for i in range(loops): tree = BinaryTree() val = randint(MIN_INT_32, MAX_INT_32) tree.insert(Node(val)) assert (tree.size == 1) assert (tree.height == 0) print("Passed" + divider)
def testBFSSingleInsert(): print(divider + "Executing testBFSSingleInsert()...") nodes = [] tree = BinaryTree() tree.insert(Node(7)) nodes = tree.getNodesBFS() print(nodesToString(nodes)) assert (nodes[0].data == 7) print("Passed" + divider)
def testSequentialInsert(): print(divider + "Executing testSequentialInsert()...") tree = BinaryTree() for i in range(1, 11): tree.insert(Node(i)) assert (tree.root.data == 1) assert (tree.size == 10) #print("Tree height is {}, expected to be {}".format(tree.height, 9)) assert (tree.height == 9) print("Passed" + divider)
def testBFSRandom(): print(divider + "Executing testBFSRandom()...") tree = BinaryTree() expectedNodes = [32, 16, 50, 2, 30, 48, 53, 5, 18, 12] for num in randomNumbers: tree.insert(Node(num)) bfsNodes = tree.getNodesBFS() print(nodesToString(bfsNodes)) # Ensure that the order of the nodes is in the proper order for BFS for i in range(0, len(expectedNodes)): assert (bfsNodes[i].data == expectedNodes[i]) print("Passed" + divider)
def testRandomInsert(): print(divider + "Executing testRandomInsert()...") numbers = [7, 2, 10, 4, 3, 1, 5, 8, 6, 9] tree = BinaryTree() for number in numbers: tree.insert(Node(number)) assert (tree.root.data == 7) assert (tree.size == 10) print("Tree height is {}, expected to be {}".format(tree.height, 4)) tree.printDFS() print() tree.printBFS() assert (tree.height == 4) print("Passed" + divider)
def testDFSRandom(): print(divider + "Executing testDFSRandom()...") tree = BinaryTree() expectedNodes = [32, 16, 2, 5, 12, 30, 18, 50, 48, 53] for number in randomNumbers: tree.insert(Node(number)) assert (tree.size == len(randomNumbers)) nodes = tree.getNodesDFS() print("Returned nodes = {}".format(nodesToString(nodes))) print("Expected nodes = {}".format([n for n in expectedNodes])) # Ensure that the order of the nodes is in the proper order for DFS for i in range(0, len(nodes)): assert (nodes[i].data == expectedNodes[i]) print("Passed" + divider)
def testFind(): print(divider + "Executing testFind()...") tree = BinaryTree() lowerBound = 0 upperBound = 100 # Insert values for i in range(lowerBound, upperBound): tree.insert(Node(i)) # Ensure all inserted values are found for i in range(lowerBound, upperBound): assert (tree.find(i, tree.root)) # Ensure values outside of range are not found for i in range(-10000, lowerBound): assert (not tree.find(i, tree.root)) for i in range(upperBound, 10000): assert (not tree.find(i, tree.root)) print("Passed " + divider)
def main(): # Driver code to build binary tree root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print('###################') postOrder(root) print() print('###################') inOrder(root) print() print('###################') print(inOrder_stack(root)) print('###################') preOrder(root) print('###################') print(height(root)) print('###################') givenLevel(root, 3) print() givenLevel(root, 2) print() givenLevel(root, 1) print() givenLevel(root, 0) print('###################') levelOrder(root) print('###################') levelOrder_queue(root) print('###################') print(maxDepth(root)) print('###################') print(diameter(root))
from binaryTree import Node def reverse(node): """ 二叉树翻转 :param node: 根节点 :return: """ node.left, node.right = node.right, node.left if node.left: reverse(node.left) if node.right: reverse(node.right) if __name__ == '__main__': node = Node(6) data = [9, 5, 2, 1, 3, 4, 7] for i in data: node.insert(i) node.treeGraph(indent=0) node.inOrder() print node.postOrder() print reverse(node) node.treeGraph(indent=0) node.inOrder() print node.postOrder()
def postOrderEx(): tree = Tree() n1 = Node('A') # I n2 = Node('M') # N n3 = Node('A') # S n4 = Node('Z') # C n5 = Node('O') # R n6 = Node('N') # E n7 = Node(' ') n8 = Node(' ') n9 = Node('<') n0 = Node('3') n0.left = n6 n0.right = n9 n6.left = n1 n6.right = n5 n5.left = n2 n5.right = n4 n4.right = n3 n9.left = n8 n8.right = n7 tree.root = n0 return tree
from binaryTree import Node from treeTraverse import * node = Node(5) node.left=Node(3) node.right= Node(6) node.left.left = Node(2) node.left.right =Node(4) node.right.right = Node(7) target = 10 # use two sum in array node_list = inorderTraverse(node) def twoSum(arr,target): """ O(n) solution for two sum """ maxVal = max(arr) help_list= [0] * (maxVal +1) for j in range(len(arr)): need = target - arr[j] if need < maxVal: if help_list[need] == 1: return True help_list[arr[j]] += 1 return False print (twoSum(node_list, target)) # Do not use two sum in array
from binaryTree import Node t1 = Node(1) t1.left = Node(2) t1.right = Node(3) t2 = Node(1) t2.left = Node(2) t2.right = Node(3) def treeToList(t): if t == None: return [] result = [t.val] return result + treeToList(t.left) + treeToList(t.right) def isSameTree(t, s): t_list = treeToList(t) s_list = treeToList(s) return s_list == t_list def isSame(t, s): if not t and not s: return True if t and s: if t.val == s.val: return isSame(t.left, s.left) and isSame(t.right, s.right) return False
from binaryTree import Node from treeTraverse import * from levelTraverseTree import * def pathSum(root, target): if not root: return [] if not root.left and not root.right and root.val == target: return [[root.val]] temp = pathSum(root.left, target-root.val) + pathSum(root.right, target-root.val) return [[root.val] + i for i in temp] target = 22 root = Node(5) root.left = Node(4) root.right = Node(8) root.left.left = Node(11) root.left.left.left = Node(7) root.left.left.right = Node(2) root.right.left = Node(13) root.right.right = Node(4) root.right.right.right = Node(1) root.right.right.left = Node(5) print (pathSum(root, target))
# GUI for Task Organizer layout = [ [sg.Text('Task Organizer')], [sg.Text('Task Name: ', size=(15, 1)), sg.InputText(do_not_clear=False)], #do_not_clear=False clears the input box everytime event is True [sg.Text('Priority: ', size=(15, 1)), sg.InputText(do_not_clear=False)], [sg.Button('Add'), sg.Button('Done'), sg.Button('Clear')], [sg.Output(size=(80, 10))] ] window = sg.Window('Task Organizer App').Layout(layout) root = Node(None, None) #dict = {'LOW': 1, 'MEDIUM': 2, 'HIGH': 3} while True: event, values = window.Read() if event is None: break elif event == 'Add': print(values[0], values[1]) root.insert(values[0], int(values[1])) elif event == 'Done': print('SIZE:') print(root.getSize()) print('TREE:') root.PrintTree()
from binaryTree import Node root = Node(1) root.left = Node(2) root.right = Node(3) root.right.left = Node(4) root.right.right = Node(5) # these are dfs of the tree def inorderTraverse(tree): """ left root right """ if not tree: return [] return inorderTraverse(tree.left) + [tree.val] + inorderTraverse( tree.right) def preorderTraverse(tree): """ root left right """ if not tree: return [] return [tree.val] + preorderTraverse(tree.left) + preorderTraverse( tree.right) def postorderTraverse(tree): """
temp_node = queue.pop(0) if temp_node.left: queue.append(temp_node.left) else: temp_node.left = node return if temp_node.right: queue.append(temp_node.right) else: temp_node.right = node return # driver code if __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) # print('Inorder traversal: ') # printInorder(root) # if(searchNode(root, 400)): # print('YES') # else: # print('NO') new_node = Node(100) insertNode(root, new_node) printInorder(root)
[sg.Text('Task Name: ', size=(18, 1)), sg.InputText(do_not_clear=False)], #do_not_clear=False clears the input box everytime event is True [sg.Text('Priority: ', size=(18, 1)), sg.InputText(do_not_clear=False)], [ sg.Text('Due Date (YYYYMMDD): ', size=(18, 1)), sg.InputText(do_not_clear=False) ], [sg.Button('Add'), sg.Button('Done'), sg.Button('Clear')], ] mainWindow = sg.Window('Task Organizer App').Layout(layout) treeWindow_active = False root = Node(None, 0, 0) treeData = sg.TreeData() def insertTree(root): if root.left: insertTree(root.left) treeData.Insert("", root.task, root.task, root.data) if root.right: insertTree(root.right) while True: event, values = mainWindow.Read() if event is None:
def insert(self, value): if self.node is None: self.node = Node.Node(value) else: self.node.insert(value)
from binaryTree import Node from letterFrequencies import english_alphabet_frequencies import queue our_priority_queue = queue.PriorityQueue() for letter in english_alphabet_frequencies: our_priority_queue.put(letter) while our_priority_queue.qsize() > 1: left = our_priority_queue.get() right = our_priority_queue.get() new_node = Node(left, right) new_tuple = (left[0] + right[0], new_node) our_priority_queue.put((new_tuple)) # LI note: your new_tuple needed to # be in parentheses. # Traverse through tree producing Huffman codes for each letter def tree_traversal(tree_root, prefix="", code={}): if isinstance(tree_root[1].left[1], Node): tree_traversal(tree_root[1].left, prefix + "0", code) else: code[tree_root[1].left[1]] = prefix + "0" if isinstance(tree_root[1].right[1], Node): tree_traversal(tree_root[1].right, prefix + "1", code) else: code[tree_root[1].right[1]] = prefix + "1" return (code)
import PySimpleGUI as sg from binaryTree import Node # GUI for Task Organizer layout = [ [sg.Text('Task Organizer')], [sg.Text('Task Name: ', size=(15,1)), sg.InputText()], [sg.Text('Priority: ', size=(15,1)), sg.InputCombo(['LOW', 'MEDIUM', 'HIGH'], size=(20,3))], [sg.Button('Add'), sg.Button('Done')] ] window = sg.Window('Task Organizer App').Layout(layout) root = Node(None) dict = {'LOW': 1, 'MEDIUM': 2, 'HIGH': 3} while True: event, values = window.Read() if event is not None and event == 'Add': print(event, dict[values[1]]) root.insert(dict[values[1]]) if event == 'Done' or event is None: print('SIZE:') print(root.getSize()) print('TREE:') root.PrintTree() break window.Close()
from binaryTree import Node from treeTraverse import * node = Node(3) node.left = Node(20) node.right = Node(9) node.left.left = Node(7) node.left.right = Node(15) node_list = preorderTraverse(node) node_list.sort() n = len(node_list) print(node_list) def arrToBST(arr, root): """ just apply sorted array to BST """ if not root: return arrToBST(arr, root.left) root.val = arr[0] arr.pop(0) arrToBST(arr, root.right) def binTreeToBST(root): if not root: return None arr = inorderTraverse(root) arr.sort()
return list = None if len(lists) == level: list = [] list.append(root) lists.append([]) else: list = lists[level] list.append(root) createLevelLinkedList(root.left, level + 1) createLevelLinkedList(root.right, level + 1) ten = TreeNode(10) eight = TreeNode(8) eight.left = TreeNode(6) eight.right = TreeNode(9) twelve = TreeNode(12) eight.left ten.left = eight ten.right = twelve sol = createLevelLinkedList(ten, 0) for i in lists: print(i)
def inOrderEx(): tree = Tree() n1 = Node("T") n2 = Node("H") n3 = Node("N") n4 = Node("A") n5 = Node("U") n6 = Node("Y") n7 = Node("K") n8 = Node("O") n6.left = n7 n6.right = n8 n5.left = n6 n3.left = n4 n3.right = n5 n2.left = n1 n2.right = n3 tree.root = n2 return tree
# 'b' '-' # / \ # '/' 'e' # / \ # 'c' 'd' # (a + (b * ((c/d) - e))) from binaryTree import Tree, Node if __name__ == "__main__": tree = Tree() n1 = Node("a") n2 = Node("+") n3 = Node("*") n4 = Node("b") n5 = Node("-") n6 = Node("/") n7 = Node("c") n8 = Node("d") n9 = Node("e") n6.left = n7 n6.right = n8 n5.left = n6 n5.right = n9