def prepost(pr, pr_s, pr_e, po, po_s, po_e, n): """ :type pr:list :type pr_s:int :type pr_e:int :type po:list :type po_s:int :type po_e:int :type n:dict :param pr: :param pr_s: :param pr_e: :param po: :param po_s: :param po_e: :param n: :return: """ if pr_s > pr_e or po_s > po_e: return None head = Node(pr[pr_s]) index = n.get(pr[pr_s + 1]) head.left = prepost(pr, pr_s + 1, pr_s + 1 + index - po_s, po, po_s, index, n) head.right = prepost(pr, pr_s + 2 + index - po_s, po, index + 1, po_e - 1, n) return head
def test_delete_with_right(self): root = Node(data=3) root.left = Node(data=1) root.left.right = Node(data=2) root = self.binary_tree.delete(node=root, data=1) assert root.left.data == 2
def tree_creator(arr, parent=None): # if arr is empty if len(arr) == 0: return None node = Node(arr[0]) node.parent = parent # if there is only one node in the array if len(arr) == 1: return node subArr = arr[1:] left = [] right = [] for i in range(len(subArr)): if subArr[i] < node.data: left.append(subArr[i]) else: right = subArr[i:] break node.left = tree_creator(left, node) node.right = tree_creator(right, node) return node
def generate_huffman_tree(array): while len(array) > 1: array.sort(key=lambda array: array[0]) first = array.pop(0) second = array.pop(0) node = Node(first[0] + second[0]) if type(first[1]) is str: node.left = Node(first[1]) else: node.left = first[1] if type(second[1]) is str: node.right = Node(second[1]) else: node.right = second[1] array.append((first[0] + second[0], node)) return array[0][1]
def infpost(i, ii, ie, p, ps, pe, n): """ :type i:list :type ii:int :type ie:int :type p:list :type ps:int :type pe:int :type n:dict :param i: :param ii: :param ie: :param p: :param ps: :param pe: :param n: :return: """ if ii > ie or ps > pe: return n head = Node(p[pe]) index = n.get(p[pe]) head.left = infpost(i, ii, index - 1, p, ps, ps + index - 1 - ii, node) head.right = infpost(i, index + 1, ie, p, ps + index - ii, pe - 1, node) return head
def preinf(p, ps, pe, i, ii, ie, n): """ :type p:list :type ps:int :type pe:int :type i:list :type ii:int :type ie:int :type n:dict :param p: :param ps: :param pe: :param i: :param ii: :param ie: :param n: :return: """ if ps > pe: return n head = Node(p[ps]) index = n.get(p[ps]) head.left = preinf(p, ps + 1, ps + index - ii, i, ii, index - 1, node) head.right = preinf(p, ps + index + 1 - ii, pe, i, index + 1, ie, node) return head
def test_lookup(self): root = Node(data='two') root.left = Node(data='one') root.right = Node(data='tww') assert self.binary_tree.lookup(node=root, data='one') is True assert self.binary_tree.lookup(node=root, data='two') is True assert self.binary_tree.lookup(node=root, data='tww') is True
def test_rank_right(self): root = Node(data=4) root.left = Node(data=1) root.left.right = Node(data=3) root.right = Node(data=6) root.right.left = Node(data=5) assert self.binary_tree.rank(node=root, data=6) == 5
def _insert_value(self, node, data): if node is None: node = Node(data) else: if data <= node.data: node.left = self._insert_value(node.left, data) else: node.right = self._insert_value(node.right, data) return node
def recurse(i, j): if j - i == 0: return None mid = j // 2 + i // 2 root = Node(val=vals[mid]) root.left = recurse(i, mid) root.right = recurse(mid + 1, j) return root
def test_delete_with_both_children(self): root = Node(data=4) root.left = Node(data=2) root.left.left = Node(data=1) root.left.right = Node(data=3) root = self.binary_tree.delete(node=root, data=2) assert root.left.data == 3 assert root.left.left.data == 1
def _insert_value(self, node, data): if node is None: node = Node(data) else: # 주어진 이진 트리에 무작위로 배치하기 위한 알고리즘 random_case = randint(0, 10) if random_case >= randint(0, self.random_level): node.left = self._insert_value(node.left, data) else: node.right = self._insert_value(node.right, data) return node
def clone(head): """ 克隆头节点 :type head:Node :param head: :return: """ if head is None: return head res = Node(head.value) res.left = clone(head.left) res.right = clone(head.right) return res
def helper(start, end): if start >= end: return [None] if start > end else [Node(start)] res = [] for i in range(start, end): left = helper(start, i) right = helper(i + 1, end) for j in left: for k in right: node = Node(i) node.left = j node.right = k res.append(node) return res
def rebuild(value, start, end): if start > end: return None head = Node(value[end]) little_end = 0 large_start = end for i in range(start, end + 1): if value[i] < value[end]: little_end = i else: large_start = i if large_start == end else large_start head.left = rebuild(value, start, little_end) head.right = rebuild(value, large_start, end - 1) return head
def btree1(): el1 = Node(1) el2 = Node(2) el3 = Node(3) el4 = Node(4) el5 = Node(5) el6 = Node(6) el1.left = el2 el1.right = el3 el1.left.left = el4 el1.left.right = el5 el1.left.left.left = el6 return BinaryTree(el1)
def rebuild_tree(value_list): """ 利用列表保存的二叉树节点值重建二叉树 :param value_list: :return: """ if not len(value_list): return node_value = value_list.pop(0) if node_value == "#": return None node = Node(node_value) node.left = rebuild_tree(value_list) node.right = rebuild_tree(value_list) return node
def list_to_binary(list): if len(list) == 0: return None if len(list) == 1: node = Node(list[0]) return node else: center_index = math.floor(len(list) / 2) left_tree = list[:center_index] right_tree = list[center_index + 1:] node = Node(list[center_index]) if len(left_tree) > 0: node.left = list_to_binary(left_tree) if len(right_tree) > 0: node.right = list_to_binary(right_tree) return node
def generate(value, start, end): """ 利用value[start,end]生产平衡搜索二叉树 :type value:list :type start:int :type end:int :param value: :param start: :param end: :return: """ if start > end: return None mid = (start + end) // 2 head = Node(value[mid]) head.left = generate(value, start, mid - 1) head.right = generate(value, mid + 1, end) return head
def minimal_tree_helper(inp_array, start, end): """ Recursively create a minimal tree, inserting the middle node as the root, left ones of the middle node to the left of the node and right one's to the right of the root node 1 2 3 4 5 6 7 :param inp_array: array :param start: start index of this array :param end: end index of this array :return: root of the tree """ if start > end: return None mid = (start + end) // 2 node = Node(inp_array[mid]) node.left = minimal_tree_helper(inp_array, start, mid - 1) node.right = minimal_tree_helper(inp_array, mid + 1, end) return node
def parse_token(tokens): """ parse tokens from lexical_parse.py; 1. trait tokens in "()" as a expression token; 2. find the lowest operator; 3. binary split tokens with lowest operator; 4. process left tokens and right tokens :param tokens: token list, the toke could be number, operator, scope and expression :return: syntax binary tree """ token_size = len(tokens) if token_size == 0: raise SyntaxError("empty token") elif token_size == 1: token = tokens[0] token_type = token.type token_value = token.value if token_type == TYPE_OPERATOR: raise SyntaxError("expression should be number or sub expression, but %s is an operator" % token_value) elif token_type == TYPE_SCOPE: raise SyntaxError("expression should be number or sub expression, but %s is a parentheses" % token_value) elif token_type == TYPE_NUM: return Node(token) else: # expression need to binary split tokens = token_value # token is a expression, split it with operator # split tokens with () token_without_parentheses = _split_sub_expression(tokens) # find lowest operator lowest_priority_operator_index = _find_lowest_priority_operator(token_without_parentheses) if lowest_priority_operator_index == -1: raise SyntaxError("can not find operator") # split left_sub_tokens = token_without_parentheses[:lowest_priority_operator_index] right_sub_tokens = token_without_parentheses[lowest_priority_operator_index + 1:] node = Node(token_without_parentheses[lowest_priority_operator_index]) node.left = parse_token(left_sub_tokens) node.right = parse_token(right_sub_tokens) return node
def from_in_pre(ino, pre, start, end, preidx): """ Construct tree from given inorder and preorder traversal arrays *Algorithm - First element of pre order traversal is root of the tree whose position in in-order traversal - divides into left sub-tree and right sub-tree. """ if start>end: return None root = Node(pre[preidx[0]]) preidx[0] = preidx[0] + 1 if start == end: return root inidx = ino.index(root.data, start, end+1) root.left = BuildTree.from_in_pre(ino, pre, start, inidx-1, preidx) root.right = BuildTree.from_in_pre(ino, pre, inidx+1, end, preidx) return root
def generate(start, end): """ 生产中序遍历为{start,start+1...end-1,end}的所有二叉树 :rtype: list :type start:int :type end:int :param start: :param end: :return: """ result = [] if start > end: return result.append(None) for i in range(start, end + 1): head = Node(i) left = generate(start, i) right = generate(i + 1, end + 1) for l in left: for r in right: head.left = clone(l) head.right = clone(r) result.append(head) return result
def k_smallest_pair(nums1, nums2, k): q, res = [(nums1[0] + nums2[0], 0, 0)], [] while k > 0: a, b = heapq.heappop(q)[1:] res.append((nums1[a], nums2[b])) k -= 1 if a + 1 < len(nums1): heapq.heappush(q, (nums1[a + 1] + nums2[b], a + 1, b)) if b + 1 < len(nums2): heapq.heappush(q, (nums1[a] + nums2[b + 1], a, b + 1)) return res if __name__ == '__main__': print('leetcode 366') root = Node(1) root.left = Node(2) root.left.left = Node(4) root.left.right = Node(5) root.right = Node(3) print(find_binary_leaf(root)) head = LinkNode(1) head.next = LinkNode(2) head.next.next = LinkNode(3) print(visit(plus_one(head))) head = LinkNode(1) head.next = LinkNode(9) print(visit(plus_one(head))) print(k_smallest_pair([1, 7, 11], [2, 4, 6], 3)) print(k_smallest_pair([1, 1, 2], [1, 2, 3], 2))
### Grade 2 , Semester 1 , Chapter 4 , Number 2 ### from binary_tree import BinaryTree, Node # (2-1-4-1 binary_tree.py를 binary_tree.py로 이름 변경 필요) if __name__ == '__main__': t = BinaryTree() # 이진트리 객체 생성 # 8개의 노드 생성 n1 = Node(100) n2 = Node(200) n3 = Node(300) n4 = Node(400) n5 = Node(500) n6 = Node(600) n7 = Node(700) n8 = Node(800) # 트리 만들기 n1.left = n2 n1.right = n3 n2.left = n4 n2.right = n5 n3.left = n6 n3.right = n7 n4.left = n8 t.root = n1 # 트리높이 및 4가지 트리순회 print('트리 높이 =', t.height(t.root)) print('전위순회:\t', end='') t.preorder(t.root) print('\n중위순회:\t', end='') t.inorder(t.root) print('\n후위순회:\t', end='') t.postorder(t.root)
from binary_tree import BinaryTree, Node if __name__ == '__main__': t = BinaryTree() # 이진트리 객체 t 생성 n1 = Node(100) # 8개의 노드 생성 n2 = Node(200) n3 = Node(300) n4 = Node(400) n5 = Node(500) n6 = Node(600) n7 = Node(700) n8 = Node(800) n1.left = n2 # n1의 왼쪽 자식-> n2 n1.right = n3 # n1의 오른쪽 자식-> n3 n2.left = n4 # n2의 왼쪽 자식-> n4 n2.right = n5 # n2의 오른쪽 자식-> n5 n3.left = n6 # n3의 왼쪽 자식-> n6 n3.right = n7 # n3의 오른쪽 자식-> n7 n4.left = n8 # n4의 왼쪽 자식-> n8 t.root = n1 # t의 루트노드를 n1으로 print('트리 높이 =', t.height(t.root)) print('전위순회:\t', end='') t.preorder(t.root) print('\n중위순회:\t', end='') t.inorder(t.root) print('\n후위순회:\t', end='') t.postorder(t.root) print('\n레벨순회:\t', end='') t.levelorder(t.root)
from binary_tree import BinaryTree, Node if __name__ == '__main__': t = BinaryTree() n1 = Node(100) n2 = Node(200) n3 = Node(300) n4 = Node(400) n5 = Node(500) n6 = Node(600) n7 = Node(700) n8 = Node(800) n1.left = n2 n1.right = n3 n2.left = n4 n2.right = n5 n3.left = n6 n3.right = n7 n4.left = n8 t.root = n1 print(f'트리 높이 = {t.height(t.root)}') print('전위 순회:\t', end='') t.preorder(t.root) print('\n중위 순회:\t', end='') t.inorder(t.root) print('\n후위 순회:\t', end='') t.postorder(t.root) print('\n레벨 순회:\t', end='')
from binary_tree import Node def path_sum(root, num, path=[]): if sum(path) + root.value == num: print path + [root.value] if root.left: path_sum(root.left, num, path+[root.value]) if root.right: path_sum(root.right, num, path+[root.value]) if __name__ == '__main__': root = Node(1) root.left, root.right = Node(2), Node(1) root.left.left, root.left.right = Node(1), Node(0) root.right.left, root.right.right = Node(1), Node(3) print """ root = 1 2 1 1 0 1 3 """ print 'now running path_sum(root, 3)' path_sum(root, 3)
node.left.data, node.right.data, ) return False else: return True if __name__ == '__main__': """ Successfull Case """ binary_tree = BinaryTree() for value in [5, 2, 1, 9, 10, 0, 6]: binary_tree.insert(value) if is_bst(binary_tree.root): print "its a BST" else: print "it not a BST" """ Root is null case """ is_bst(None) """ Unsuccessful case """ # Lets construct an invalid tree parent_node = Node(5) parent_node.left = Node(6) parent_node.right = Node(8) if is_bst(parent_node): print "its a BST" else: print "it not a BST"
elif left: return is_bst(left, min, value) elif right: return is_bst(right, value, max) return True return False """ BST 4 2 6 1 3 5 7 BT 4 2 6 1 8 5 7 """ if __name__ == '__main__': bst = Node(4) bst.left, bst.right = Node(2), Node(6) bst.left.left, bst.left.right = Node(1), Node(3) bst.right.left, bst.right.right = Node(5), Node(7) bt = Node(4) bt.left, bt.right = Node(2), Node(6) bt.left.left, bt.left.right = Node(1), Node(8) bt.right.left, bt.right.right = Node(5), Node(7) print 'is_bst(bst) =', is_bst(bst) print 'is_bst(bt) =', is_bst(bt)
def test_min_left(self): root = Node(data='b') root.left = Node(data='a') assert self.binary_tree.min(node=root).data == 'a'
merge = True else: tmp.append(str(1)) helper(start + 1) if merge: tmp[-1] = str(int(tmp[-1]) - 1) else: tmp.pop() helper(0) return res if __name__ == '__main__': print('leetcode 313, 320') root = Node(3) root.left = Node(9) root.right = Node(20) root.right.left = Node(15) root.right.right = Node(7) print(vertical_order(root)) root = Node(3) root.left = Node(9) root.left.left = Node(4) root.left.right = Node(5) root.right = Node(20) root.right.left = Node(2) root.right.right = Node(7) print(vertical_order(root)) print(remove_duplicate('bcabc')) print(remove_duplicate('cbacdcbc')) print(generate_abbre('word'))
num = c + num return st.pop() def find_disappear_number(nums): i = 0 while i < len(nums): if nums[i] != nums[nums[i] - 1]: nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] else: i += 1 return [i for i, v in enumerate(nums) if i != v - 1] if __name__ == '__main__': print('leetcode 437') root = Node(10) root.left = Node(5) root.left.left = Node(3) root.left.right = Node(2) root.left.left.left = Node(3) root.left.left.right = Node(-2) root.left.right = Node(2) root.left.right.right = Node(1) root.right = Node(-3) root.right.right = Node(11) print(path_sum(root, 8)) print(parse_ternary('T?2:3')) print(parse_ternary('F?1:T?4:5')) print(parse_ternary('T?T?F:5:3')) print(find_disappear_number([4, 3, 2, 7, 8, 2, 3, 1]))