def ConvertToBinaryTree(self): # assignment 4 order = Queue() next_level = Queue() root = binary_tree.binary_tree(self.store[0]) branch = root current = self while True: if len(current.store[1]) > 0: child1 = current.store[1][0] branch.AddLeft(binary_tree.binary_tree(child1.store[0])) if len(current.store[1]) > 1: temp = Queue() temp.enqueue(branch.store[1]) for i in current.store[1]: temp.enqueue(i) next_level.enqueue(temp) if order.length() > 0: next1 = order.dequeue() branch.AddRight(binary_tree.binary_tree(next1.store[0])) current = next1 branch = branch.store[2] continue elif next_level.length() > 0: order = next_level.dequeue() branch = order.dequeue() current = order.dequeue() else: return root return root
def create_binary(left, right, post_index): if left > right or post_index >= len(postorder) or post_index < 0: return if left == right: return binary_tree(postorder[post_index]) else: root = binary_tree(postorder[post_index]) root.left = create_binary(left, inorder.index(postorder[post_index]) - 1, post_index - (right-inorder.index(postorder[post_index]) + 1)) """post_index减去右子树的个数,得到左子树节点的索引信息""" root.right = create_binary(inorder.index(postorder[post_index]) + 1, right, post_index - 1) return root
def BinaryProcess(self, binaryTree): if len(self.store[1]) == 0: return False extender = bt.binary_tree(self.store[1][0]) binaryTree.AddLeft(extender) for i in range(1, len(self.store[1])): temp = bt.binary_tree(self.store[1][i]) extender.AddRight(temp) extender = extender.store[2] return True
def ConvertToBinaryTree(self): newBinary = binary_tree.binary_tree(self.store[0]) #are there successors? if (self.store[1] != None): for i in range(0, len(self.store[1])): #check for first successor if (i == 0): newBinary2 = self.store[1][i].ConvertToBinaryTree() #print "Left",newBinary2.store[0],"" #print "Added to",newBinary.store[0],"" newBinary.AddLeft(newBinary2) #subsequent successors else: newBinary3 = self.store[1][i].ConvertToBinaryTree() #print "Right",newBinary3.store[0],"" #print "Added to",newBinary2.store[0],"" newBinary2.AddRight(newBinary3) newBinary2 = newBinary3 return newBinary
def Recursive_Turn_To_Binary(self, root): b_tree = binary_tree.binary_tree(root.store[0]) children = [] if root.store[1] != []: for i in range(len(root.store[1])): children += [binary_tree.binary_tree(root.store[1][i].store[0])] for i in range(len(children)-1): if root.store[1][i].store[1] != []: children[i] = self.Recursive_Turn_To_Binary(root.store[1][i]) children[i].AddRight(children[i+1]) b_tree.AddLeft(children[0]) return b_tree
def ConvertToBinary_Builder(self, sibs): b = bt.binary_tree(self.store[0]) if len(self.store[1]) > 0: b.AddLeft(self.store[1][0].ConvertToBinary_Builder( self.store[1][1:len(self.store[1])])) if len(sibs) > 0: b.AddRight(sibs[0].ConvertToBinary_Builder(sibs[1:len(sibs)])) return b
def Btconvert(self, tree): #This will recursivly follow the algorith that converts tree into BT then identifies #children/converts and adds the first to the left node and the rest to the subsquent right nodes of eachother hold = [] if not tree: return False if not tree.store[1]: x = binary_tree.binary_tree(tree.store[0]) return x if len(tree.store[1]) == 1: x = binary_tree.binary_tree(tree.store[0]) x.AddLeft(self.Btconvert(tree.store[1][0])) return x else: x = binary_tree.binary_tree(tree.store[0]) x.AddLeft(self.Btconvert(tree.store[1][0])) for i in range(1, len(tree.store[1])): x.AddtoSuperRight(x.store[1][0], self.Btconvert(tree.store[1][i])) return x
def ConvertToBinaryTree(self): i=1 levelList=[] if len(self.store)==0: return False biTree=binary_tree.binary_tree(self.store[0]) while(len(self.Get_LevelList(i))!=0): levelList=levelList+[self.Get_LevelList(i)] i=i+1 biTree.buildLevel(levelList) return biTree
def create_binary(left, right, pre_index): """这里的参数分别是,中序序列的左边,右边,和root节点在先序序列中的位置,这里没必要加上root在中序序列中的位置 因为知道了pre_index就能知道了in_index。通过inorder.index(preorder[pre_index])可以得到,如果把in_index作为参数,那么 在递归的时候,preorder[pre_index+1]可能会out of list index。所以直接用在先序列表中的索引,在函数开始之前判断, 就解决这个问题啦""" if left > right or pre_index >= len(preorder) or pre_index < 0: return """这里是很重要的,因为树中不满足的话说明都是遇到了空节点,只要返回就好啦""" if left == right: return binary_tree(preorder[pre_index])#叶子节点 else: root = binary_tree(preorder[pre_index]) root.left = create_binary(left, inorder.index(preorder[pre_index]) - 1, pre_index + 1) """左子树中,root节点在先序中的索引是pre_index+1""" root.right = create_binary(inorder.index(preorder[pre_index]) + 1, right, pre_index + inorder.index(preorder[pre_index]) - left + 1) """右子树中,root节点在先序中的索引是什么?对于中序中的left到right之间的排列,是左子树,根节点,右子树 所以在先序中,root节点的索引应该是pre_index(原来的)+inorder.index(preorder[pre_index]) - left...这个是左子树的节点 个数+ 1得到右子树的节点在先序中的索引 注意一下,如果不匹配的话,是无法index的。那么如果考虑这种情况的实例的话,需要在外面判断一下""" return root#一定要加上这个return,要不然无法返回,千万不要忘记了
def ConvertToBinaryTree(self): x = binary_tree.binary_tree(self.store[0]) # for i in self.store[1]: # i.ConvertToBinaryTree() for i in range(0, len(self.store[1]), 1): y = self.store[1][i].ConvertToBinaryTree() if i == 0: x.AddLeft(y) if i == 1: x.AddRight(y) return x
def ConvertToBinaryTree_Non(self): root = bt.binary_tree(self.store[0]) newq = Queue() for v in self.store[1]: newq.enqueue(v) targ = root childPaths = Queue() children = Queue() childPaths.enqueue(newq) sibs = [] while len(childPaths.vals) > 0: first = True rt = childPaths.dequeue()[1] while True: child = rt.dequeue() if child[0] == False: break t = child[1] b = bt.binary_tree(t.store[0]) if first: targ.AddLeft(b) branch = b first = False else: sibs = sibs + [b] children.enqueue(b) newq = Queue() for vl in t.store[1]: newq.enqueue(vl) childPaths.enqueue(newq) print(childPaths.vals) for v in sibs: print(branch.store[0]) print(v.store[0]) branch.AddRight(v) branch = v sibs = [] targ = children.dequeue()[1] return root
def ConvertToBinaryTree(self): temp = queue() retval = binary_tree.binary_tree( self.store[0]) #initialize a binary tree to store our general tree for i in range(0, len(self.store[1])): subtree = self.store[1][i].ConvertToBinaryTree( ) #recursively convert subtrees temp.Enqueue(subtree) #add the convert subtrees to the queue while (temp.length() > 1): a = temp.anti_dequeue() #pop the first two nodes b = temp.anti_dequeue() b.AddRight(a) #make the siblings right sucessors temp.Enqueue(b) leftcheck = temp.Dequeue() if isinstance( leftcheck, binary_tree.binary_tree ): #Ensure that we're adding a subtree, not an incorrect type. #This prevents a bug where garbage is added. Exercise: Make the function work without this patch. retval.AddLeft(leftcheck) return retval #Return the binary tree
Time Complexity: O(N) in number of elements, O(log(n)) in depth Space Complexity: O(n) in depth ''' if bt is None: ''' Base case''' return 0 left_depth = get_depth(bt.left_child) right_depth = get_depth(bt.right_child) if left_depth is False or right_depth is False: return False elif abs(right_depth - left_depth) > 1: return False depth = max(left_depth, right_depth) + 1 return depth def is_balanced(bt): rv = get_depth(bt) if rv is False: return False return True if __name__ == "__main__": print "Test" bt = binary_tree(0, 0, binary_tree(1, 1), binary_tree(2, 1)) print "Should be true - is %r" % is_balanced(bt) bt.right_child.add_children(3, 4) bt.right_child.right_child.add_children(5, 6) print "Should be false - is %r" % is_balanced(bt)
def setUp(self): self.tree = binary_tree.binary_tree() self.tree(12, 8, 7, 3, 7, 17, 15, 14, 16, 19, 18, 20) self.empty_tree = binary_tree.binary_tree()
return None ''' Recursive Step continues ''' return_list.insert(0, [bt, t]) return return_list def common_ancestor(bt_root, node1, node2): node1_path = path_from_root(bt_root,node1) node2_path = path_from_root(bt_root, node2) for i in range(min(len(node1_path), len(node2_path))): node1_element = node1_path[i] node2_element = node2_path[i] if node1_element[1] != node2_element[1]: return node1_element if len(node1_path) == len(node2_path): return None elif len(node1_path) < len(node2_path): return node1_path[-1] else: return node2_path[-1] if __name__ == "__main__": bt = binary_tree(0, 0, binary_tree(1,1, binary_tree(3,2), binary_tree(4,2)), binary_tree(2,1, binary_tree(5,2), binary_tree(6,2))) print "Test" print "Expect 2 - got ",common_ancestor(bt, 5, 6)[0].id
w=tree.tree(6) v=tree.tree(7) r = tree.tree(8) u = tree.tree(2) x.AddSuccessor(y) x.AddSuccessor(z) c=tree.tree(5) z.AddSuccessor(c) y.AddSuccessor(w) y.AddSuccessor(v) w.AddSuccessor(r) y.AddSuccessor(u) test = binary_tree.binary_tree(100) test2 = binary_tree.binary_tree(200) test3 = binary_tree.binary_tree(300) test4 = binary_tree.binary_tree(400) test5 = binary_tree.binary_tree(500) test6 = binary_tree.binary_tree(600) test7 = binary_tree.binary_tree(7) test.AddLeft(test2) test.AddRight(test3) test2.AddLeft(test4) test2.AddRight(test5) test3.AddLeft(test6) test5.AddRight(test7)
''' BFS: Time Complexity: O(V + E) Space Complexity: O(V) traversal_queue is a queue represented by a list linked_lists is a list of linked lists represented by a list of lists ''' traversal_queue = [] linked_lists = [] linked_lists.append([bt.id]) traversal_queue.append((bt.left_child, True)) traversal_queue.append((bt.right_child, False)) for node in traversal_queue: if node[0] is None: continue if node[1] is True: traversal_queue.append((node[0].left_child, True)) linked_lists.append([node[0].id]) traversal_queue.append((node[0].right_child, False)) else: traversal_queue.append((node[0].left_child, False)) linked_lists[-1].append(node[0].id) traversal_queue.append((node[0].right_child, False)) return linked_lists if __name__ == "__main__": bt = binary_tree(0, 0, binary_tree(1,1), binary_tree(2,1)) ll = make_linked_list(bt) print ll
import tree import binary_tree x = tree.tree(1000) y = tree.tree(2000) z = tree.tree(3000) x.AddSuccessor(y) x.AddSuccessor(z) w = tree.tree(5) z.AddSuccessor(w) ans = x.Get_LevelOrder() print "Level order Tree" + str(ans) bin = x.ConvertToBinaryTree() bin1 = bin.Get_LevelOrder() print bin1 a = binary_tree.binary_tree(1) a.AddLeft(2) a.AddRight(3) a.AddLeft(4) a.AddRight(5) ans2 = a.Get_LevelOrder() print ans2 ans3 = a.ConvertToTree() final = ans3[1].Get_LevelOrder() print final
def binary(list): tree = binary_tree.binary_tree() for item in list: tree(item) return tree.sorted_tree()
def main(): y = binary_tree(100) y.AddLeft(200) y.AddRight(300) y.getRight().AddLeft(1) print(y.Get_LevelOrder()) y.getLeft().AddLeft(2) y.getLeft().AddRight(4) y.getRight().AddRight(3) print(y.Get_LevelOrder()) y.AddLeft(1) print(y.Get_LevelOrder()) x = tree("g") x.AddSuccessor(tree("i")) x.AddSuccessor(tree("j")) x.AddSuccessor(tree("k")) y = tree("c") y.AddSuccessor(tree("f")) y.AddSuccessor(x) y.AddSuccessor(tree("h")) z = tree("a") z.AddSuccessor(tree("b")) z.AddSuccessor(y) z.AddSuccessor(tree("d")) z.AddSuccessor(tree("e")) x = binary_tree("j") x.AddRight("k") y = binary_tree("i") y.AddRight(x) m = binary_tree("g") m.AddLeft(y) m.AddRight("h") q = binary_tree("f") q.AddRight(m) w = binary_tree("d") w.AddRight("e") c = binary_tree("c") c.AddLeft(q) c.AddRight(w) b = binary_tree("b") b.AddRight(c) a = binary_tree("a") a.AddLeft(b) print("Tree Form") print(z.Get_LevelOrder()) z.Print_DepthFirst() print("BT to Tree Form") print(a.ConvertToTree()[1].Get_LevelOrder()) a.ConvertToTree()[1].Print_DepthFirst() print("Binary Tree Form") print(a.Get_LevelOrder()) a.Print_DepthFirst() print("Tree to BT Form") print(z.ConvertToBinaryTree().Get_LevelOrder()) z.ConvertToBinaryTree().Print_DepthFirst() print("BT to Tree Test: " + str(z.Get_LevelOrder() == a.ConvertToTree()[1].Get_LevelOrder())) print("Tree to BT Test: " + str(a.Get_LevelOrder() == z.ConvertToBinaryTree().Get_LevelOrder()))
from binary_tree import binary_tree from grid import Grid grid = Grid(10, 10) binary_tree(grid) print(grid)
print("Equivalent Binary Tree") print(b.Get_LevelOrder()) print("Testing ...") g = b.ConvertToTree() if g[0]: print(g[1].Get_LevelOrder()) #convert to general tree ''' Tree: 1 2 3 4 5 ''' print("Binary Trees") x = binary_tree.binary_tree(1) a = binary_tree.binary_tree(2) x.AddLeft(a) y = binary_tree.binary_tree(3) y.AddLeft(binary_tree.binary_tree(4)) y.AddRight(binary_tree.binary_tree(5)) x.AddRight(y) print("Tree Zero:") print(x.Get_LevelOrder()) t = x.ConvertToTree() if t[0]: print(t[1].Get_LevelOrder()) else: print("Cannot Convert") ''' Tree: 1
from node import Node from binary_tree import binary_tree import random tree = binary_tree(head=Node(15)) nodes = [1, 2, 3, 5, 7, 12, 19, 23, 29, 31, 37, 41] random.shuffle(nodes) print(nodes) for node in nodes: tree.add_node(Node(node)) #print(tree.depth()) #for node in tree.head: # print(node) print("in order traversal") tree.in_order() print("----------") print("pre order traversal") tree.pre_order() print("----------") #tree.delete(37) #nodes.remove(37) #print(tree.count) #print("new tree: ") #tree.in_order()
def ConvertToBinaryTree(self): v = binary_tree.binary_tree(3) return v
def ConvertToBinaryTree(self): binaryTree = bt.binary_tree(self) self.Bind(binaryTree) return binaryTree