def haffman_tree(string): frequency = Counter(string) tree = {} for freq in frequency.most_common(): root = Node(freq[1]) root.left = Node(ord(freq[0])) if root.value in tree: tree[root.value].append(root) else: tree[root.value] = [root] m = min(tree.keys()) while len(tree) != 1 or m is not None: nodes = [0, 0] for i in range(len(nodes)): nodes[i] = tree[m].pop() if not tree[m]: tree.pop(m) try: m = min(tree.keys()) except ValueError: m = None root = Node(nodes[0].value + nodes[1].value) root.left = nodes[0] root.right = nodes[1] if root.value in tree: tree[root.value].append(root) else: tree[root.value] = [root] return tree[min(tree.keys())][0]
def constructMaximumBinaryTree(nums): if len(nums) == 1: node = Node(nums[0]) return node max_value = nums[0] max_index = 0 for i in range(1, len(nums)): if nums[i] > max_value: max_value = nums[i] max_index = i node = Node(max_value) if max_index == 0: right_subarray = nums[1:] node.right = constructMaximumBinaryTree(right_subarray) elif max_index == len(nums) - 1: left_subarray = nums[:-1] node.left = constructMaximumBinaryTree(left_subarray) else: left_subarray = nums[:max_index] node.left = constructMaximumBinaryTree(left_subarray) right_subarray = nums[max_index + 1:] node.right = constructMaximumBinaryTree(right_subarray) return node
def test_prune(): def self_prune(target, node_id): return target.prune(node_id) for invalid_tree in ['foo', -1, None]: with pytest.raises(ValueError) as err: prune(invalid_tree, 0) assert str(err.value) == 'Expecting a list or a node' for prune_func in [prune, self_prune]: root = Node(1) for bad_id in ['foo', None]: with pytest.raises(ValueError) as err: prune_func(root, bad_id) assert str(err.value) == 'The node ID must be an integer' with pytest.raises(ValueError) as err: prune_func(root, -1) assert str(err.value) == 'The node ID must start from 0' with pytest.raises(ValueError) as err: prune_func(root, 0) assert str(err.value) == 'Cannot prune the root node' with pytest.raises(ValueError) as err: prune_func(root, 10) assert str(err.value) == 'Cannot find node with ID 10' root.left = Node(2) assert prune_func(root, 1) == root assert root.left is None root.left = Node(2) root.right = Node(3) assert prune_func(root, 1) == root assert root.left is None assert attr(root, 'right.value') == 3 root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.left = Node(6) root.left.right.right = Node(7) assert prune_func(root.left.right, 2) == root.left.right assert attr(root, 'left.right.right') is None assert prune_func(root, 4) == root assert attr(root, 'left.right') is None assert prune_func(root, 1) == root assert attr(root, 'left') is None assert attr(root, 'right.value') == 3 assert prune_func(root, 1) == root assert attr(root, 'right') is None
def test_node_set_attributes(): root = Node(1) assert root.left is None assert root.right is None assert root.value == 1 assert repr(root) == 'Node(1)' left_child = Node(2) root.left = left_child assert root.left is left_child assert root.right is None assert root.value == 1 assert root.left.left is None assert root.left.right is None assert root.left.value == 2 assert repr(left_child) == 'Node(2)' right_child = Node(3) root.right = right_child assert root.left is left_child assert root.right is right_child assert root.value == 1 assert root.right.left is None assert root.right.right is None assert root.right.value == 3 assert repr(right_child) == 'Node(3)' last_node = Node(4) left_child.right = last_node assert root.left.right is last_node assert root.left.right.value == 4 assert repr(last_node) == 'Node(4)' with pytest.raises(InvalidNodeValueError): # noinspection PyTypeChecker Node('this_is_not_an_integer') with pytest.raises(InvalidNodeTypeError): # noinspection PyTypeChecker Node(1, 'this_is_not_a_node') with pytest.raises(InvalidNodeTypeError): # noinspection PyTypeChecker Node(1, Node(1), 'this_is_not_a_node') with pytest.raises(InvalidNodeValueError): root.value = 'this_is_not_an_integer' assert root.value == 1 with pytest.raises(InvalidNodeTypeError): root.left = 'this_is_not_a_node' assert root.left is left_child with pytest.raises(InvalidNodeTypeError): root.right = 'this_is_not_a_node' assert root.right is right_child
def bstFromPreorder(preorder): node = Node(preorder[0]) if len(preorder) == 1: return node right_tree_root = None for i in range(1, len(preorder)): if preorder[i] > preorder[0]: right_tree_root = i break if right_tree_root != None: if right_tree_root >= 2: node.left = bstFromPreorder(preorder[1:right_tree_root]) node.right = bstFromPreorder(preorder[right_tree_root:]) else: node.left = bstFromPreorder(preorder[1:]) return node
def _identical(root): if root is None: return root tree = Node(root.data) tree.left = _identical(root.left) tree.right = _identical(root.right) return tree
def test_root_node( self): # Test case where root is a node of interest for lca root = Node(2) root.left = Node(1) lca1 = lca.findLCA(root, 1, 2) assert lca1.value is 2, "test_root_node failed"
def test_get_root_number(): tree = Node(123) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) assert get_root_number(tree) == 123
def drawTree(v): if v == None: return None r = Node(v.data) r.left = drawTree(v.left) r.right = drawTree(v.right) return r
def constructTree(preOrder, inOrder): # 忽略参数合法性判断 if len(preOrder) == 0: return None # 前序遍历的第一个结点一定是根结点 rootData = preOrder[0] root = Node(rootData) root.left = None root.right = None for i in range(0, len(inOrder)): if inOrder[i] == rootData: break # 递归构造左子树和右子树 root.left = constructTree(preOrder[1:1 + i], inOrder[:i]) root.right = constructTree(preOrder[1 + i:], inOrder[i + 1:]) return root
def reConstructBinaryTree(pre, tin): # the first element in pre list is the root root = Node(pre[0]) # find the index of the root value in tin list root_index = 0 for i in range(len(tin)): if tin[i] == root.value: root_index = i # remove the root from the pre list del pre[0] # build left subtree if root_index > 0: left = tin[:root_index] root.left = reConstructBinaryTree(pre[:len(left) + 1], left) # remove the elements of left subtree in pre list pre = pre[len(left):] # build right subtree if root_index < len(tin) - 1: right = tin[root_index + 1:] root.right = reConstructBinaryTree(pre, right) return root
def _mirror(root): if root is None: return root node = Node(root.data) node.left = _mirror(root.right) node.right = _mirror(root.left) return node
def test_leafs(): def self_leafs(target, values_only): return target.leafs(values_only) def to_set(nodes): return set(attr(node, 'value') for node in nodes) for invalid_tree in ['foo', -1, None]: with pytest.raises(ValueError) as err: leafs(invalid_tree) assert str(err.value) == 'Expecting a list or a node' for leafs_func in [leafs, self_leafs]: root = Node(1) assert set(leafs_func(root, True)) == {1} assert to_set(leafs_func(root, False)) == {1} root.left = Node(2) assert set(leafs_func(root, True)) == {2} assert to_set(leafs_func(root, False)) == {2} root.right = Node(3) assert set(leafs_func(root, True)) == {2, 3} assert to_set(leafs_func(root, False)) == {2, 3} root.left.left = Node(4) assert set(leafs_func(root, True)) == {3, 4} assert to_set(leafs_func(root, False)) == {3, 4} root.left.right = Node(5) assert set(leafs_func(root, True)) == {3, 4, 5} assert to_set(leafs_func(root, False)) == {3, 4, 5}
def test_cats(): # chars = ['c','a','t','s'] # freq = ['000','01','10','111'] # frequencies = {'c':'000','a':'01','t':'10','s':'111'} # val = '*' # root = Node(val) # for key, value in frequencies.items(): # [insert(root, x, val) for x in value, if x == '0': val = '*', else x == '1': val = '*'] # # replase last insertion with key # insert(root, x, key) root = Node('*') root.left = Node('*') root.left.right = Node('a') root.left.left = Node('*') root.left.left.left = Node('c') root.right = Node('*') root.right.left = Node('t') root.right.right = Node('*') root.right.right.right = Node('s') print(root)
def buildSearchTree(nums, ret, node=None): """迭代需要搞清楚每一次计算得到了什么, 在这个函数里就是给当前节点添加两个子叶 Args: nums: a list or tuple, which need sorted. node: instance of `binarytree.Node`, or None """ # (1,2,3,4,5,7,8) # 一个非子叶节点的左孩比它小, 右孩比它大 # nums.sort() length = len(nums) if length == 0: return else: mid = length // 2 # 偏右 if node is None: node = Node(nums[mid]) ret.append(node) if mid > 0: # length is 1 buildSearchTree(nums[:mid], ret, node) buildSearchTree(nums[mid + 1:], ret, node) else: if node.left is None: # 先序构建 node.left = Node(nums[mid]) buildSearchTree(nums[:mid], ret, node.left) buildSearchTree(nums[mid + 1:], ret, node.left) else: node.right = Node(nums[mid]) buildSearchTree(nums[mid + 1:], ret, node.right) buildSearchTree(nums[:mid], ret, node.right)
def insert_huffman_tree(root, key, value): list(key) if root is None: root = Node(value) else: if key == '0': root.left = Node(value)
def main(): """ 1 / \\ """ root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) BinaryTree.printNode(root) queue = deque() BinaryTree.put_in_queue(queue, root) while len(queue) > 0: n = queue.popleft() print(n) print("---------------") BinaryTree.print_bfs_recursive(queue, root) print("---------------") BinaryTree.print_bfs(root)
def getNode(data): newNode = Node(data) newNode.data = data newNode.left = None newNode.right = None return newNode
def nRound(vector, root): tempRoot = root a = vector.pop() b = vector.pop() if (a + b) < 1.0: vector.append(a + b) rootn = Node(a + b) rootn.right = tempRoot rootn.left = Node(b) return nRound(vector, rootn) else: rootn = Node(a + b) rootn.right = tempRoot rootn.left = Node(b) infoRoot(rootn) return rootn
def recur(root, left, right): if left > right: return # 递归终止 node = TreeNode(preorder[root]) # 建立根节点 i = dic[preorder[root]] # 划分根节点、左子树、右子树 node.left = recur(root + 1, left, i - 1) # 开启左子树递归 node.right = recur(i - left + root + 1, i + 1, right) # 开启右子树递归 return node # 回溯返回根节点
def test_node(): node = Node(1) assert attr(node, 'left') is None assert attr(node, 'right') is None assert attr(node, 'value') == 1 assert attr(node, 'parent') is None assert repr(node) == 'Node(1)' node.left = Node(2) node.right = Node(3) assert repr(attr(node, 'left')) == 'Node(2)' assert repr(attr(node, 'right')) == 'Node(3)' assert attr(node.left, 'parent') == node assert attr(node.right, 'parent') == node node.left.left = Node(4) node.left.right = Node(5) node.right.left = Node(6) node.right.right = Node(7) assert repr(attr(node, 'left.left')) == 'Node(4)' assert repr(attr(node, 'left.right')) == 'Node(5)' assert repr(attr(node, 'right.right')) == 'Node(7)' assert repr(attr(node, 'right.left')) == 'Node(6)' assert attr(node.left.left, 'parent') == node.left assert attr(node.left.right, 'parent') == node.left assert attr(node.right.left, 'parent') == node.right assert attr(node.right.right, 'parent') == node.right assert node.is_root() is True assert node.left.is_root() is False assert node.left.right.is_leaf() is True assert node.is_leaf() is False assert node.level() == 0 assert node.right.level() == 1
def main(): root = Node(50) root.left = Node(18) root.right = Node(200) root.left.right = Node(100) print levelOrderMinSum(root)
def initNode() -> TreeNode: a = TreeNode(1) b = TreeNode(2) c = TreeNode(3) d = TreeNode(4) e = TreeNode(5) f = TreeNode(6) g = TreeNode(7) a.left = b a.right = c b.left = d b.right = e c.left = f c.right = g return a
def maketree(a): if type(a) is int: return Node(a) else: x = Node(-1) x.left = maketree(a[0]) x.right = maketree(a[1]) return x
def main(): print "Computing Longest Path" root = Node(1) root.left = Node(1) root.right = Node(2) root.left.right = Node(1) printPath(longest_path(root))
def sortedarraytoBSTrecu(self, nums, begin, end): if begin > end: return None mid = begin + (end - begin) // 2 root = TN(nums[mid]) root.left = self.sortedarraytoBSTrecu(nums, begin, mid - 1) root.right = self.sortedarraytoBSTrecu(nums, mid + 1, end) return root
def main(): print "Starting main function" root = Node(1) root.left = Node(1) root.right = Node(2) root.left.right = Node(1) dfs(root, 3)
def test_heap_float_values(): root = Node(1.0) root.left = Node(0.5) root.right = Node(1.5) assert root.height == 1 assert root.is_balanced is True assert root.is_bst is True assert root.is_complete is True assert root.is_max_heap is False assert root.is_min_heap is False assert root.is_perfect is True assert root.is_strict is True assert root.leaf_count == 2 assert root.max_leaf_depth == 1 assert root.max_node_value == 1.5 assert root.min_leaf_depth == 1 assert root.min_node_value == 0.5 assert root.size == 3 for printer in [builtin_print, pprint_default]: lines = printer([1.0]) assert lines == ['1.0'] lines = printer([1.0, 2.0]) assert lines == [' _1.0', ' /', '2.0'] lines = printer([1.0, None, 3.0]) assert lines == ['1.0_', ' \\', ' 3.0'] lines = printer([1.0, 2.0, 3.0]) assert lines == [' _1.0_', ' / \\', '2.0 3.0'] lines = printer([1.0, 2.0, 3.0, None, 5.0]) assert lines == [ ' _____1.0_', ' / \\', '2.0_ 3.0', ' \\', ' 5.0' ] for builder in [tree, bst, heap]: for _ in range(REPETITIONS): root = builder() root_copy = copy.deepcopy(root) for node in root: node.value += 0.1 assert root.height == root_copy.height assert root.is_balanced == root_copy.is_balanced assert root.is_bst == root_copy.is_bst assert root.is_complete == root_copy.is_complete assert root.is_max_heap == root_copy.is_max_heap assert root.is_min_heap == root_copy.is_min_heap assert root.is_perfect == root_copy.is_perfect assert root.is_strict == root_copy.is_strict assert root.is_symmetric == root_copy.is_symmetric assert root.leaf_count == root_copy.leaf_count assert root.max_leaf_depth == root_copy.max_leaf_depth assert root.max_node_value == root_copy.max_node_value + 0.1 assert root.min_leaf_depth == root_copy.min_leaf_depth assert root.min_node_value == root_copy.min_node_value + 0.1 assert root.size == root_copy.size
def test_tree_del_node(): root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.left = Node(6) with pytest.raises(NodeModifyError) as err: del root[0] assert str(err.value) == "cannot delete the root node" with pytest.raises(NodeIndexError) as err: del root[-1] assert str(err.value) == "node index must be a non-negative int" with pytest.raises(NodeNotFoundError) as err: del root[10] assert str(err.value) == "no node to delete at index 10" with pytest.raises(NodeNotFoundError) as err: del root[100] assert str(err.value) == "no node to delete at index 100" del root[3] assert root.left.left is None assert root.left.val == 2 assert root.left.right.val == 5 assert root.left.right.right is None assert root.left.right.left.val == 6 assert root.left.right.left.left is None assert root.left.right.left.right is None assert root.right.val == 3 assert root.right.left is None assert root.right.right is None assert root.size == 5 del root[2] assert root.left.left is None assert root.left.val == 2 assert root.left.right.val == 5 assert root.left.right.right is None assert root.left.right.left.val == 6 assert root.left.right.left.left is None assert root.left.right.left.right is None assert root.right is None assert root.size == 4 del root[4] assert root.left.left is None assert root.left.right is None assert root.right is None assert root.size == 2 del root[1] assert root.left is None assert root.right is None assert root.size == 1
def test_tree_del_node(): root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.left = Node(6) with pytest.raises(OperationForbiddenError) as err: del root[0] assert str(err.value) == 'Cannot delete the root node' with pytest.raises(InvalidNodeIndexError) as err: del root[-1] assert str(err.value) == 'The node index must be a non-negative integer' with pytest.raises(NodeNotFoundError) as err: del root[10] assert str(err.value) == 'No node to delete at index 10' with pytest.raises(NodeNotFoundError) as err: del root[100] assert str(err.value) == 'No node to delete at index 100' del root[3] assert root.left.left is None assert root.left.value == 2 assert root.left.right.value == 5 assert root.left.right.right is None assert root.left.right.left.value == 6 assert root.left.right.left.left is None assert root.left.right.left.right is None assert root.right.value == 3 assert root.right.left is None assert root.right.right is None assert root.size == 5 del root[2] assert root.left.left is None assert root.left.value == 2 assert root.left.right.value == 5 assert root.left.right.right is None assert root.left.right.left.value == 6 assert root.left.right.left.left is None assert root.left.right.left.right is None assert root.right is None assert root.size == 4 del root[4] assert root.left.left is None assert root.left.right is None assert root.right is None assert root.size == 2 del root[1] assert root.left is None assert root.right is None assert root.size == 1
def test_tree_validate(): class TestNode(Node): def __setattr__(self, attr, value): object.__setattr__(self, attr, value) root = Node(1) root.validate() # Should pass root = Node(1) root.left = Node(2) root.validate() # Should pass root = Node(1) root.left = Node(2) root.right = Node(3) root.validate() # Should pass root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.left = Node(6) root.validate() # Should pass root = TestNode(1) root.left = 'not_a_node' with pytest.raises(InvalidNodeTypeError) as err: root.validate() assert str(err.value) == 'Invalid node instance at index 1' root = TestNode(1) root.right = TestNode(2) root.right.value = 'not_an_integer' with pytest.raises(InvalidNodeValueError) as err: root.validate() assert str(err.value) == 'Invalid node value at index 2' root = TestNode(1) root.left = TestNode(2) root.left.right = root with pytest.raises(CyclicNodeReferenceError) as err: root.validate() assert str(err.value) == 'Cyclic node reference at index 4'
from binarytree import Node as TN class Solution(object): def invertbinaryTree(self, root): if root is not None: root.left, root.right = \ self.invertbinaryTree(root.right), self.invertbinaryTree(root.left) return root S = Solution() root = TN(4) root.left = TN(2) root.left = TN(2) root.right = TN(7) root.left.left = TN(1) root.left.right = TN(3) root.right.left = TN(6) root.right.right = TN(9) print root print S.invertbinaryTree(root)
class Solution(object): def identical_trees(self, tree_1, tree_2): if tree_1 is None and tree_2 is None: return True if tree_1 is not None and tree_2 is not None: return ((tree_1.value == tree_2.value) and self.identical_trees(tree_1.left, tree_2.left) and self.identical_trees(tree_1.right, tree_2.right)) return False S = Solution() root1 = Treenode(1) root1.left = Treenode(2) root1.right = Treenode(3) root1.left.left = Treenode(4) root1.left.right = Treenode(5) print root1 root2 = Treenode(1) root2.left = Treenode(2) root2.right = Treenode(3) root2.left.left = Treenode(4) root2.left.right = Treenode(5) print root2 if S.identical_trees(root1, root2): print "Trees are identical" else:
return s == 0 else: ans = 0 # Otherwise check both subtrees subSum = s - root.value # If we reach a leaf node and sum becomes 0, then # return True if (subSum == 0 and root.left == None and root.right == None): return True if root.left is not None: ans = ans or self.roottoleafpathSum(root.left, subSum) if root.right is not None: ans = ans or self.roottoleafpathSum(root.right, subSum) return ans S = Solution() s = 21 root = TN(10) root.left = TN(8) root.right = TN(2) root.left.right = TN(5) root.left.left = TN(3) root.right.left = TN(2) print(root) print S.roottoleafpathSum(root, s)
def k_path_sum(self, root, k): if root is None: return #print 'Visiting {}'.format(root.value) self.path.append(root.value) self.k_path_sum(root.left, k) self.k_path_sum(root.right, k) #print 'Current path: {}'.format(self.path) currsum = 0 for i in reversed(xrange(len(self.path))): currsum += self.path[i] if currsum == k: print self.path[i:] self.path.pop() root = Treenode(1) root.left = Treenode(3) root.left.left = Treenode(2) root.left.right = Treenode(1) root.left.right.left = Treenode(1) root.right = Treenode(-1) root.right.left = Treenode(4) root.right.left.left = Treenode(1) root.right.left.right = Treenode(2) root.right.right = Treenode(5) root.right.right.right = Treenode(2) print(root) S = Solution() S.k_path_sum(root, 5)
def create_tree(self, nums, root, i): if i < len(nums): root = TN(nums[i]) root.left = self.create_tree(nums, root.left, 2 * i + 1) root.right = self.create_tree(nums, root.right, 2 * i + 2) return root
from collections import deque """ deque: double-ended queue """ # Build a tree with binarytree.tree seed(3) my_tree = tree(height = 3, is_perfect = False) #print("Generate with built-in tree method") #print(type(my_tree)) # <class 'binarytree.Node'> #print(my_tree) # Build with Node root = Node(1) root.left = Node(2) root.right = Node(3) #print("Generate with built-in Node method") #print(root) #print(root.value) # Build tree using a list data1 = [10,5,-3,3,2,None,11,3,-2,None,1] data2 = [3,5,2,1,4,6,7,8,9,10,11,12,13,14] def create_btree_with_list(data): tree = Node(data.pop(0)) fringe = deque([tree]) while len(data) > 1: