def testFromList(): lst = [1, 2, 3, 4, '#', '#', 5] expect = TreeNode(1, left=TreeNode(2, left=TreeNode(4)), right=TreeNode(3, right=TreeNode(5))) assert str(fromList(lst)) == str(expect) assert fromList([]) == None
def recoverFromPreorder(self, S: str) -> TreeNode: if not S: return None S += '-' # 加一个字符保证最后一个节点也能入栈 stack = [] # 节点堆栈 lvl, val = 0, None for c in S: if c.isdigit(): if val is None: val = 0 val = val * 10 + int(c) else: if val != None: # 节点入栈 if stack: top, topLvl = stack[-1] while topLvl >= lvl: stack.pop() top, topLvl = stack[-1] node = TreeNode(val) if top.left: top.right = node else: top.left = node stack.append((node, lvl)) else: stack.append((TreeNode(val), lvl)) lvl, val = 0, None # 入栈之后重置 lvl += 1 # 层级加1 return stack[0][0]
def rebuild_tree(pre_order, in_order, length): """ 根据前序遍历和中序遍历重建二叉树 所构建的二叉树是否唯一?参考:https://www.cnblogs.com/jiaxin359/p/9512348.html :param pre_order: :param in_order: :param length: :return: """ if len(pre_order) == 0 or len(in_order) == 0 or length <= 0: return None i = 0 tn = pre_order[0] root = TreeNode(tn) while i < length and in_order[i] != tn: i += 1 if i == length: return None root.left = rebuild_tree(pre_order[1:], in_order, i) root.right = rebuild_tree(pre_order[i + 1:], in_order[i + 1:], length - i - 1) return root
def sorted_array_to_bst(self, nums): """ Converted an array of nums into a tree. Args: nums -- An array of nums sorted in ascending order. Returns: TreeNode """ # Time: O(n) where n is the number of items in the list. # Space: O(1) if not nums: return None n = len(nums) if n % 2 == 0: mid = int(n / 2) - 1 else: mid = int(n / 2) node = TreeNode(nums[mid]) node.left = self.sorted_array_to_bst(nums[:mid]) node.right = self.sorted_array_to_bst(nums[mid + 1:]) return node
def invertTree(self, root: TreeNode) -> TreeNode: if root: right = root.right left = root.left root.right = self.invertTree(left) root.left = self.invertTree(right) return root
def buildTree(self, preorder: list, inorder: list) -> TreeNode: if preorder: root = TreeNode(preorder[0]) mid = inorder.index(preorder[0]) root.left = self.buildTree(preorder[1:mid+1], inorder[0:mid]) root.right = self.buildTree(preorder[mid+1:len(preorder)], inorder[mid+1:len(inorder)]) return root
def string_to_tree_node(string): string = string.strip() string = string[1:-1] if not string: return None input_values = [s.strip() for s in string.split(',')] root = TreeNode(int(input_values[0])) node_queue = [root] front = 0 index = 1 while index < len(input_values): node = node_queue[front] front = front + 1 item = input_values[index] index = index + 1 if item != "null": left_number = int(item) node.left = TreeNode(left_number) node_queue.append(node.left) if index >= len(input_values): break item = input_values[index] index = index + 1 if item != "null": right_number = int(item) node.right = TreeNode(right_number) node_queue.append(node.right) return root
def create(nums: list) -> TreeNode: if not nums: return node = TreeNode(nums[len(nums) // 2]) node.left = create(nums[:len(nums) // 2]) node.right = create(nums[len(nums) // 2 + 1:]) return node
def invertTree(self, root: TreeNode) -> TreeNode: if root: left = self.invertTree(root.right) right = self.invertTree(root.left) root.left = left root.right = right return root
def test_is_symmetric_2(self): node5 = TreeNode(3, None, None) node4 = TreeNode(3, None, None) node3 = TreeNode(2, None, node5) node2 = TreeNode(2, None, node4) node1 = TreeNode(1, node2, node3) test = self.leet101.is_symmetric(node1) self.assertEqual(test, False)
def test_max_depth_1(self): node4 = TreeNode(7, None, None) node3 = TreeNode(15, None, None) node2 = TreeNode(20, node3, node4) node1 = TreeNode(9, None, None) root = TreeNode(3, node1, node2) test = self.leet104.max_depth(root) self.assertEqual(test, 3)
def test_min_depth_1(self): node5 = TreeNode(7, None, None) node4 = TreeNode(15, None, None) node3 = TreeNode(20, node4, node5) node2 = TreeNode(9, None, None) node1 = TreeNode(3, node2, node3) test = self.leet112.has_path_sum(node1, 12) self.assertEqual(test, True)
def test_sorted_array_to_bst_1(self): node5 = TreeNode(5, None, None) node4 = TreeNode(-10, None, None) node3 = TreeNode(9, node5, None) node2 = TreeNode(-3, node4, None) node1 = TreeNode(0, node2, node3) test = self.leet108.sorted_array_to_bst([-10, -3, 0, 5, 9]) self.assertEqual(test.val, 0)
def buildTree(self, inorder: list, postorder: list) -> TreeNode: if inorder: root = TreeNode(postorder[len(postorder) - 1]) mid = inorder.index(postorder[len(postorder) - 1]) root.left = self.buildTree(inorder[0:mid], postorder[0:mid]) root.right = self.buildTree(inorder[mid + 1:len(inorder)], postorder[mid:len(inorder) - 1]) return root
def test_is_balanced_1(self): node5 = TreeNode(7, None, None) node4 = TreeNode(15, None, None) node3 = TreeNode(20, node4, node5) node2 = TreeNode(9, None, None) node1 = TreeNode(3, node2, node3) test = self.leet110.is_balanced(node1) self.assertEqual(test, True)
def helper(start, end): if start > end: return None mid = start + (end - start) // 2 root = TreeNode(A[mid]) root.left = helper(start, mid - 1) root.right = helper(mid + 1, end) return root
def test_min_depth_1(self): node5 = TreeNode(7,None,None) node4 = TreeNode(15,None,None) node3 = TreeNode(20,node4,node5) node2 = TreeNode(9,None,None) node1 = TreeNode(3,node2,node3) test = self.leet111.min_depth(node1) self.assertEqual(test, 2)
def insert(root: TreeNode, val: int) -> TreeNode: if not root: return TreeNode(val) elif val < root: root.left = insert(root.left, val) else: root.right = insert(root.right, val) return root
def inorder(node: TreeNode) -> str: ret_value: str = "" if node.get_left_child() is not None: ret_value += "(" + inorder(node.get_left_child()) ret_value += str(node.get_root_value()) if node.get_right_child() is not None: ret_value += inorder(node.get_right_child()) + ")" return ret_value
def buildBST(nums: List[int], lb: int, ub: int) -> TreeNode: if lb > ub: return None mid = (lb + ub) >> 1 node = TreeNode(nums[mid]) node.left = buildBST(nums, lb, mid - 1) node.right = buildBST(nums, mid + 1, ub) return node
def postorder(node: TreeNode) -> str: if node is None: return None left = postorder(node.get_left_child()) right = postorder(node.get_right_child()) if left is not None and right is not None: f = opers[node.get_root_value()] return f(left, right) else: return node.get_root_value()
def sortedListToBST(self, head: ListNode) -> TreeNode: if not head: return None mid = self.getMidNode(head) root = TreeNode(mid.val) if head == mid: return root root.left = self.sortedListToBST(head) root.right = self.sortedListToBST(mid.next) return root
def test_node_init(self): n = TreeNode(factor="amount", level=3, value=5, w=-0.1434, lo_branch="empty", hi_branch="empty") self.assertEqual("amount", n.factor) n = TreeNode(**{'obj': 33.33}) self.assertEqual(33.33, n.obj)
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if not t1: return t2 elif not t2: return t1 t = TreeNode(t1.val + t2.val) t.left = self.mergeTrees(t1.left, t2.left) t.right = self.mergeTrees(t1.right, t2.right) return t
def test_graft_doubly_links_parent_and_child(self): parent = TreeNode(name = 'parent') child = TreeNode(name = 'child') parent.graft_child(child) #assert children of parent are correct child_ids_of_parent = [id(c) for c in parent.children] child_ids_of_parent_spec = [id(child)] self.assertItemsEqual(child_ids_of_parent, child_ids_of_parent_spec) #assert parent of children is correct self.assertEqual(id(child.parent), id(parent))
def main(): root = TreeNode(1) root.left = TreeNode(0) root.right = TreeNode(1) root.left.left = TreeNode(1) root.right.left = TreeNode(6) root.right.right = TreeNode(5) print("Total Sum of Path Numbers: " + str(find_sum_of_path_numbers(root)))
def main(): root = TreeNode(12) root.left = TreeNode(7) root.right = TreeNode(1) root.left.left = TreeNode(4) root.right.left = TreeNode(10) root.right.right = TreeNode(5) print("Tree has paths: " + str(count_paths(root, 11)))
def flatten(self, root: TreeNode) -> None: if root is None: return numList = [] self.preOrder(root, numList) root.val = numList[0] root.left = None cur = root for i in range(1, len(numList)): cur.right = TreeNode(numList[i]) cur = cur.right
def createMinimalBst(arr, start, end): if end < start: return None mid = (start+end)/2 print "Mid:", mid, arr[mid] n = TreeNode(arr[mid]) n.left = createMinimalBst(arr, start, mid-1) n.right = createMinimalBst(arr, mid+1, end) print "left, mid, right", n.left, n, n.right return n
def __init__(self, parent, depth, name, kids): TreeNode.__init__(self, parent) m = paren_re.match(name) if m: self.name = m.group(1) self.nondefault = True else: self.name = name self.nondefault = False self.parent = parent self.depth = depth self.grabChildren(kids)
def loadfromInitData(self): rootNode = TreeNode(0,'root') tempid = 100 for key in data: parentNode = TreeNode(tempid,key,parent=rootNode) for leaf in data[key]: leafNode = TreeNode(leaf[0],leaf[1],color=leaf[2],accu=leaf[3],parent=parentNode) tempid += 1 self.mymodel = rootNode for node in self.mymodel.children: self.myscene.addItem(NodeGraphicsItem(node))
def import_node(self, iter, key, tree): type = get_json_type(tree) if type == "Array": new_iter = self.insert(iter, -1, row=[TreeNode(key, [])]) for child in tree: self.import_node(new_iter, None, child) elif type == "Object": new_iter = self.insert(iter, -1, row=[TreeNode(key, {})]) for child_key, child in tree.items(): self.import_node(new_iter, child_key, child) else: self.insert(iter, -1, row=[TreeNode(key, tree)])
def createPop(self, popsize): ''' Need to create trees here. ''' pop = [] for i in range(popsize): depth = 2 root = TreeNode() root.setRoot() createTree(depth, root) counter = 0 #printTree(counter, root) initTree(root, self.geneLen, self.random) ind = Individual(self.random, length = 0, genome = root) self.decode(ind) pop.append(ind) return pop
def nodeLinkage(self): top=TreeNode(0,self.pytree) members=self.pytree.getNodeWild(':*') self.assertEqual((members==top.member_nids).all(),True) self.assertEqual((members==top.getMembers()).all(),True) self.assertEqual(top.member.nid_number,members[0].nid_number) member=top.member for idx in range(1,len(members)): self.assertEqual(member.brother.nid_number,members[idx].nid_number) member=member.brother children=self.pytree.getNodeWild('.*') self.assertEqual((children==top.children_nids).all(),True) self.assertEqual((children==top.getChildren()).all(),True) self.assertEqual(top.child.nid_number,children[0].nid_number) child=top.child for idx in range(1,len(children)): self.assertEqual(child.brother.nid_number,children[idx].nid_number) child=child.brother self.assertEqual(top.child.nid_number,self.pytree.getNode(str(top.child)).nid_number) self.assertEqual(top.child.child.parent.nid_number,top.child.nid_number) x=array(int32(0)).repeat(len(members)+len(children)) x[0:len(members)]=members.nid_number.data() x[len(members):]=children.nid_number.data() self.assertEqual((makeArray(x)==top.descendants.nid_number).all(),True) self.assertEqual((top.descendants.nid_number==top.getDescendants().nid_number).all(),True) self.assertEqual(top.child.child.depth,3) self.assertEqual(top.getNumDescendants(),len(x)) self.assertEqual(top.getNumMembers(),len(members)) self.assertEqual(top.getNumChildren(),len(children)) self.assertEqual(top.number_of_members,len(members)) self.assertEqual(top.number_of_children,len(children)) self.assertEqual(top.number_of_descendants,len(x)) devs=self.pytree2.getNodeWild('\\PYTREESUB::TOP.***','DEVICE') dev=devs[0].conglomerate_nids self.assertEqual((dev.nid_number==devs[0].getConglomerateNodes().nid_number).all(),True) self.assertEqual((dev.conglomerate_elt==makeArray(array(range(len(dev)))+1)).all(),True) for idx in range(len(dev)): self.assertEqual(dev[idx].conglomerate_elt,idx+1) self.assertEqual(dev[idx].getConglomerateElt(),idx+1) self.assertEqual(top.child.is_child,True) self.assertEqual(top.child.is_member,False) self.assertEqual(top.member.is_child,False) self.assertEqual(top.member.is_member,True) self.assertEqual(top.child.is_child,top.child.isChild()) self.assertEqual(top.child.is_member,top.child.isMember()) ip=self.pytree2.getNode('\\ip') self.assertEqual(ip.fullpath,"\\PYTREE::TOP.PYTREESUB:IP") self.assertEqual(ip.fullpath,ip.getFullPath()) self.assertEqual(ip.minpath,"\\IP") self.assertEqual(ip.minpath,ip.getMinPath()) self.assertEqual(ip.node_name,'IP') self.assertEqual(ip.node_name,ip.getNodeName()) self.assertEqual(ip.path,"\\PYTREESUB::IP") self.assertEqual(ip.path,ip.getPath()) return
def test_simple_binary_tree_with_three_levels_has_4_leaves(self): #first level a0 = TreeNode(name='a0') #second level b0 = TreeNode(name='b0') b1 = TreeNode(name='b1') #third level c0 = TreeNode(name='c0') c1 = TreeNode(name='c1') c2 = TreeNode(name='c2') c3 = TreeNode(name='c3') #attach everything a0.graft_child(b0) a0.graft_child(b1) b0.graft_child(c0) b0.graft_child(c1) b1.graft_child(c2) b1.graft_child(c3) #confirm leaves leaf_names = [leaf.name for leaf in a0.leaves] leaf_names_spec = ['c0','c1','c2','c3'] self.assertItemsEqual(leaf_names, leaf_names_spec)
def test_trim_removes_double_link_between_parent_and_child_to_avoid_cycles(self): parent = TreeNode(name = 'parent') child = TreeNode(name = 'child') parent.graft_child(child) child.trim() #assert child no longer in children of parent child_ids_of_parent = [id(c) for c in parent.children] child_ids_of_parent_spec = list() self.assertItemsEqual(child_ids_of_parent, child_ids_of_parent_spec) #assert parent is None for the child self.assertIsNone(child.parent)
def test_TN_string_representation_displays_all_data_items_and_relatives_summary(self): parent = TreeNode() main = TreeNode(a=1, b=2) parent.graft_child(main) main.graft_child(TreeNode()) main.graft_child(TreeNode()) string_spec = 'TreeNode:\n'\ ' parent: yes\n'\ ' children: 2\n'\ ' a: 1\n'\ ' b: 2' self.assertEqual(str(main), string_spec)
if node.left is None: r = find_arrays_from_bst(node.right) elif node.right is None: r = find_arrays_from_bst(node.left) else: for left_arr in find_arrays_from_bst(node.left): for right_arr in find_arrays_from_bst(node.right): r.extend(permute_with_partial_ordering(left_arr, right_arr)) res = [] for item in r: item.insert(0, node.val) res.append(item) return res root = TreeNode(2) root.left = TreeNode(1) root.right = TreeNode(3) root.right.right = TreeNode(10) root = TreeNode(12) root.left = TreeNode(10) root.right = TreeNode(14) root.left.left = TreeNode(9) root.left.right = TreeNode(11) root.right.left = TreeNode(13) root.right.left.right = TreeNode(13.5) root.right.right = TreeNode(16) root.right.right.right = TreeNode(17) root.right.right.right.right = TreeNode(19)
def test_node_self_identifies_as_not_leaf_if_any_children(self): node = TreeNode() node.graft_child(TreeNode()) self.assertFalse(node.is_leaf)
def test_trim_on_a_node_with_no_parent_does_nothing(self): node = TreeNode() node.trim() self.assertIsNone(node.parent) #still None
curr = queue.popleft() curr_sum = sums[curr] if curr.left: sums[curr.left] = curr_sum + curr.left.val queue.append(curr.left) maxSum = max(maxSum, sums[curr.left]) if curr.right: sums[curr.right] = curr_sum + curr.right.val queue.append(curr.right) maxSum = max(maxSum, sums[curr.right]) del(sums[curr]) return maxSum root = TreeNode(1) root.left = TreeNode(2) root.left.left = TreeNode(3) root.left.right = TreeNode(4) root.left.right.left = TreeNode(10) root.left.right.right = TreeNode(7) root.left.left.left = TreeNode(9) root.left.left.right = TreeNode(8) root.right = TreeNode(5) root.right.right = TreeNode(6) print root.print_tree(root) print '----------------'
def setUp(self): self.root = TreeNode(name = 'root') self.a = TreeNode(name = 'a') self.b = TreeNode(name = 'b') self.c = TreeNode(name = 'c')
class Traversing_A_Tree(ut.TestCase): def setUp(self): self.root = TreeNode(name = 'root') self.a = TreeNode(name = 'a') self.b = TreeNode(name = 'b') self.c = TreeNode(name = 'c') def test_node_generates_in_order_traversal_from_self(self): self.root.graft_child(self.a) self.root.graft_child(self.b) self.b.graft_child(self.c) names = [node.name for node in self.root.in_order_nodes] names_spec = ['root', 'a', 'b', 'c'] self.assertSequenceEqual(names, names_spec) def test_node_generates_post_order_traversal_from_self(self): self.root.graft_child(self.a) self.root.graft_child(self.b) self.b.graft_child(self.c) names = [node.name for node in self.root.post_order_nodes] names_spec = ['c', 'b', 'a', 'root'] self.assertSequenceEqual(names, names_spec) def test_node_generates_only_self_when_no_parent_or_children(self): node_string_list_spec = ['root'] node_string_list = [node.name for node in self.root.in_order_nodes] self.assertEqual(node_string_list_spec, node_string_list) def test_node_generates_only_nodes_including_and_below_self_in_tree(self): self.root.graft_child(self.a) self.root.graft_child(self.b) self.b.graft_child(self.c) names = [node.name for node in self.b.in_order_nodes] names_spec = ['b', 'c'] #i.e. 'a' is not in there self.assertSequenceEqual(names, names_spec)
def __decision_tree(self,X,Y,features,level,metric,classes): # returns the root of the Decision Tree(which consists of TreeNodes) built after fitting the training data # Here Nodes are printed as in PREORDER traversl # classes represents the different classes present in the classification problem # metric can take value gain_ratio or gini_index # level represents depth of the tree # We split a node on a particular feature only once (in a given root to leaf node path) # If the node consists of only 1 class if len(set(Y)) == 1: print("Level",level) output = None for i in classes: if i in Y: output = i print("Count of",i,"=",len(Y)) else : print("Count of",i,"=",0) if metric == "gain_ratio": print("Current Entropy is = 0.0") elif metric == "gini_index": print("Current Gini Index is = 0.0") print("Reached leaf Node") print() return TreeNode(None,output) # If we have run out of features to split upon # In this case we will output the class with maximum count if len(features) == 0: print("Level",level) freq_map = self.__count_unique(Y) output = None max_count = -math.inf for i in classes: if i not in freq_map: print("Count of",i,"=",0) else : if freq_map[i] > max_count : output = i max_count = freq_map[i] print("Count of",i,"=",freq_map[i]) if metric == "gain_ratio": print("Current Entropy is =",self.__entropy(Y)) elif metric == "gini_index": print("Current Gini Index is =",self.__gini_index(Y)) print("Reached leaf Node") print() return TreeNode(None,output) # Finding the best feature to split upon max_gain = -math.inf final_feature = None for f in features : if metric == "gain_ratio": current_gain = self.__gain_ratio(X,Y,f) elif metric =="gini_index": current_gain = self.__gini_gain(X,Y,f) if current_gain > max_gain: max_gain = current_gain final_feature = f print("Level",level) freq_map = self.__count_unique(Y) output = None max_count = -math.inf for i in classes: if i not in freq_map: print("Count of",i,"=",0) else : if freq_map[i] > max_count : output = i max_count = freq_map[i] print("Count of",i,"=",freq_map[i]) if metric == "gain_ratio" : print("Current Entropy is =",self.__entropy(Y)) print("Splitting on feature X[",final_feature,"] with gain ratio ",max_gain,sep="") print() elif metric == "gini_index": print("Current Gini Index is =",self.__gini_index(Y)) print("Splitting on feature X[",final_feature,"] with gini gain ",max_gain,sep="") print() unique_values = set(X[:,final_feature]) # unique_values represents the unique values of the feature selected df = pd.DataFrame(X) # Adding Y values as the last column in the dataframe df[df.shape[1]] = Y current_node = TreeNode(final_feature,output) # Now removing the selected feature from the list as we do not want to split on one feature more than once(in a given root to leaf node path) index = features.index(final_feature) features.remove(final_feature) for i in unique_values: # Creating a new dataframe with value of selected feature = i df1 = df[df[final_feature] == i] # Segregating the X and Y values and recursively calling on the splits node = self.__decision_tree(df1.iloc[:,0:df1.shape[1]-1].values,df1.iloc[:,df1.shape[1]-1].values,features,level+1,metric,classes) current_node.add_child(i,node) # Add the removed feature features.insert(index,final_feature) return current_node
def test_children_is_a_sequence(self): node = TreeNode() node.graft_child(TreeNode()) self.assertTrue(node.children) #True, e.g. not empty list
elif val < curr.val: succ = curr curr = curr.left elif val > curr.val: pred = curr curr = curr.right return str(pred), str(succ) # r = TreeNode(10) # r.left = TreeNode(9) # r.left.right = TreeNode(9.1) # r.left.left = TreeNode(8) # r.right = TreeNode(20) # r.right.left = TreeNode(15) # r.right.left.right = TreeNode(17) # r.right.left.right.left = TreeNode(16) # r.right.left.right.left.right = TreeNode(16.1) # r.right.left.right.right = TreeNode(18) # r.right.right = TreeNode(200) # r.right.right.right = TreeNode(220) # same tree as above^ but with parent links enabled r = TreeNode(10) for v in [9, 9.1, 8, 20, 15, 17, 16, 16.1, 18, 200, 220]: r.insert(v) node_in_question = r.right.right.right print find_successor_from_node(r, node_in_question) print find_successor_from_node_using_parent_links(node_in_question) print get_predecessor_successor(r, node_in_question.val)
def get_height(t): left_height = 0 right_height = 0 if t is None: return -1 if t.left is not None: h = get_height(t.left) if h < 0: return -1 left_height = h if t.right is not None: h = get_height(t.right) if h < 0: return -1 right_height = h if abs(left_height - right_height) > 1: return -1 return max(left_height, right_height) + 1 def is_balanced(t): return get_height(t) >= 0 root = TreeNode(10) root.left = TreeNode(20) root.left.left = TreeNode(20) root.right = TreeNode(2) root.right.right = TreeNode(2) root.right.right.right = TreeNode(2) print is_balanced(root)