def convert_tree(self, input): input = input.strip() input = input[1:-1] if not input: return None inputValues = [s.strip() for s in input.split(',')] root = TreeNode(int(inputValues[0])) nodeQueue = [root] front = 0 index = 1 while index < len(inputValues): node = nodeQueue[front] front = front + 1 item = inputValues[index] index = index + 1 if item != "null": leftNumber = int(item) node.left = TreeNode(leftNumber) nodeQueue.append(node.left) if index >= len(inputValues): break item = inputValues[index] index = index + 1 if item != "null": rightNumber = int(item) node.right = TreeNode(rightNumber) nodeQueue.append(node.right) return root
def deserialize(vals): #vals = [10, 5, -3, 3, 2, None, 11, 3, -2, None, 1] #vals = [1, 2, 3] buffer = [] t_root = TreeNode(vals[0]) buffer.append(t_root) val_head = 1 while buffer: # and val_head < len(vals): next_buffer = [] for n in buffer: if val_head < len(vals): #print(n.value, val_head) # Create n_l = TreeNode(vals[val_head]) if vals[val_head] else None val_head += 1 n_r = TreeNode(vals[val_head]) if vals[val_head] else None val_head += 1 # Connect n.left = n_l n.right = n_r # pop and push if n_l: next_buffer.append(n_l) if n_r: next_buffer.append(n_r) buffer = next_buffer return t_root
def recoverFromPreorder(self, S: str) -> TreeNode: depth_to_node = {} comps = S.split("-") root_val = int(comps[0]) root = TreeNode(root_val) depth_to_node[0] = root N = len(comps) i = 1 while i < N: num_str = comps[i] depth = 1 while len(num_str) == 0: depth += 1 i += 1 num_str = comps[i] i += 1 num = int(num_str) node = TreeNode(num) parent = depth_to_node[depth - 1] depth_to_node[depth] = node if parent.left is None: parent.left = node else: parent.right = node return root
def _gap_split_new(self, angle_old, angle_new_1, angle_new_2): """ Create new nodes for angle_new_1 and angle_new_2. Parameters: angle_old (int): Angle of the gap that splitted angle_new_1 (int): First angle for new node angle_new_2 (int): Second angle for new node """ # remove node, which represents the splitted gap, from the graph self.graph_visualisation.remove_node(self.root[angle_old]) self.root[angle_old] = None # create new nodes and add to the root node1 = TreeNode() self.root[angle_new_1] = node1 node2 = TreeNode() self.root[angle_new_2] = node2 # update graph self.graph_visualisation.add_node_to_root(self.root[angle_new_1]) self.graph_visualisation.add_node_to_root(self.root[angle_new_2]) self.graph_visualisation.redraw = True
def add_node(self, added_node, target_node): ''' This function allows to add a new node on a target node if it has at least one empty child Parameters ---------- added_node : node we want to add target_node : node on which we want to add the new node ''' # If the tree doesn't exist, the root takes added_node data added_node = TreeNode(added_node) if self.root_node is None: self.root_node = Tree(added_node) #If the target_node is not a leaf and hasn't a left child #Left child takes added_node value elif target_node.is_leaf is False: if target_node.left is None: target_node.left = added_node #else, if ih hasn't right child #Right child takes added_node value else: if target_node.right is None: target_node.right = TreeNode(added_node) #else call the function starting with #the right child of the target node else: self.add_node(added_node, target_node.right)
def test_bad_construction(self): with self.assertRaises(ValueError): tn = TreeNode([[1.0, 2.0], [1.0]], [1.0, 2.0]) with self.assertRaises(ValueError): tn = TreeNode([[1.0, 2.0], [1.0, 2.0]], [1.0]) with self.assertRaises(ValueError): tn = TreeNode([[1.0], [1.0, 2.0]], [1.0, 2.0])
def _insert(self, key, val, currentNode): if key < currentNode.key: if currentNode.hasLeftChild(): self._insert(key, val, currentNode.leftChild) else: currentNode.leftChild = TreeNode(key, val, parent=currentNode) # Keep track of max height if currentNode.rightChild: pass else: self.maxheight += 1 elif key > currentNode.key: if currentNode.hasRightChild(): self._insert(key, val, currentNode.rightChild) else: currentNode.rightChild = TreeNode(key, val, parent=currentNode) #Keep track of max height if currentNode.leftChild: pass else: self.maxheight += 1 else: currentNode.payload = val self.size -= 1
def operate_tn(op, l, r): if op == ":": #':' operator adds the length of branch (and create node if no node exists) if isinstance(l, TreeNode): l.length = float(r) return l else: nod = TreeNode(name=[l], length=float( r)) #added [] 18/10/13...to give all tip names as node.name return nod elif op == ",": #',' operator creat a subtree from 2 nodes if not isinstance(l, TreeNode): l = TreeNode(name=[ l ]) #added [] 18/10/13...to give all tip names as node.name if not isinstance(r, TreeNode): r = TreeNode(name=[ r ]) #added [] 18/10/13...to give all tip names as node.name nod = TreeNode( name=l.name + r.name ) #added [] 18/10/13...to give all tip names as node.name. need refactoring. l.parent = nod r.parent = nod nod.left, nod.right = l, r return nod
def __build_tree(self, weights): # get clusters with ward_tree function pairs = ward_tree(weights.T)[0] w = weights.T n_samples = weights.T.shape[0] tree_nodes = {} idx = 0 for pair in pairs: w_list = [] children = [] for el in pair: if el < n_samples: norm_weight = w[el] / np.linalg.norm(w[el], ord=2) tree_nodes[el] = TreeNode( weights=norm_weight, right_child=None, left_child=None, class_idx=el, ) w_list.append(norm_weight) else: w_list.append(tree_nodes[el].weight) children.append(el) tree_nodes[idx + n_samples] = TreeNode( weights=(w_list[0] + w_list[1]) / 2.0, right_child=tree_nodes[children[1]], left_child=tree_nodes[children[0]], class_idx=None, ) idx += 1 return tree_nodes[idx + n_samples - 1]
def str2tree(self, s): """ :type s: str :rtype: TreeNode """ # assume input string is valid # assume no calculations in the expression dummy = TreeNode(-1) stack = [dummy] prev = 0 sign = 1 for i, char in enumerate(s): if char == '-': sign = -1 elif char in '0123456789': prev = prev * 10 + int(char) # node creation ready if i == len(s) - 1 or s[i + 1] in '()': num = sign * prev node = TreeNode(num) prev = 0 sign = 1 # append node from left to right parent = stack[-1] if not parent.left: parent.left = node elif not parent.right: parent.right = node # node is now the direct parent of next node stack.append(node) elif char == ')': stack.pop() return dummy.left
def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ # 异常处理 if data == '[]': return None # li 是列表 data 从第二位开始到倒数第二位结束的截取片段,这是为了去掉字符串两边的 '[', ']' li = data[1:-1].split(',') queue = collections.deque() # 列表第一个节点即为根节点 root = TreeNode(int(li[0])) queue.append(root) counter = 0 # 从根节点的下一位开始截取 for v in li[1:]: # 状态记录器(像寄存器),异或用来记录当前状态 if counter == 0: parent = queue.popleft() if v.strip() != 'None': cur = TreeNode(int(v)) queue.append(cur) if counter == 0: parent.left = cur else: parent.right = cur # 当 counter 为0,异或得出结果为1,否则为0 # 这样用来判断是要放到左节点还是右节点 counter ^= 1 return root
def build_tree(nums): if not nums: return None root = TreeNode(nums.pop(0)) stack = [root] while stack and nums: new_stack = [] for i in xrange(len(stack)): if len(nums) <= 0: return root else: left = TreeNode(nums.pop(0)) stack[i].left = left new_stack.append(left) if len(nums) <= 0: return root else: right = TreeNode(nums.pop(0)) stack[i].right = right new_stack.append(right) stack = new_stack return root
def test_minimal_tree_simple(self): expected = TreeNode(2) expected.left = TreeNode(1) expected.right = TreeNode(3) self.assertEqual( minimal_tree([1, 2, 3]), expected )
def _put(self, key, val, currentNode): if key < currentNode.key: if currentNode.hasLeftChild(): self._put(key, val, currentNode.leftChild) else: currentNode.leftChild = TreeNode(key, val, parent=currentNode) else: if currentNode.hasRightChild(): self._put(key, val, currentNode.rightChild) else: currentNode.rightChild = TreeNode(key, val, parent=currentNode)
def _put(self, key, val, current_node): if key < current_node.key: if current_node.has_left_child(): self._put(key, val, current_node.left_child) else: current_node.left_child = TreeNode(key, val, parent = current_node) else: if current_node.has_right_child(): self._put(key, val, current_node.right_child) else: current_node.right_child = TreeNode(key, val, parent= current_node)
def _put_helper(self, key, value, node: TreeNode) -> None: if key < node.get_key(): if node.get_left_child(): self._put_helper(key, value, node.get_left_child()) else: node.set_left_child(TreeNode(key, value, parent=node)) elif key > node.get_key(): if node.get_right_child(): self._put_helper(key, value, node.get_right_child()) else: node.set_right_child(TreeNode(key, value, parent=node)) else: node.set_value(value)
def insert(self, parent, left=None, right=None): if not self.root: self.root = TreeNode(parent) node = self.root else: node = self.bfs(parent) if node: node.left = TreeNode(left) if left else None node.right = TreeNode(right) if right else None else: raise LookupError("There is no such parent")
def _put(self, key, val, currentNode): if key < currentNode.key: if currentNode.hasLeftChild(): self._put(key, val, currentNode.leftChild) else: currentNode.leftChild = TreeNode(key, val, parent=currentNode) elif key > currentNode.key: if currentNode.hasRightChild(): self._put(key, val, currentNode.rightChild) else: currentNode.rightChild = TreeNode(key, val, parent=currentNode) else: currentNode.payload = val self.size -= 1 # since put always adds 1 and we're only updating a existing entry
def copy_tree(tree_list, idx, root): copy(tree_list, idx, root) if (2 * idx + 1) < len(tree_list): if len(tree_list[2 * idx + 1]) > 0: left = TreeNode() root.left = left copy_tree(tree_list, 2 * idx + 1, left) if 2 * idx + 2 < len(tree_list): if len(tree_list[2 * idx + 2]) > 0: right = TreeNode() root.right = right copy_tree(tree_list, 2 * idx + 2, right)
def init(): # generate reference edges rootNode = None ename2treeNode = {} for i, node in enumerate(userInput): if i == 0: ## ROOT rootNode = TreeNode(parent=None, level=-1, eid=-1, ename="ROOT", isUserProvided=True, confidence_score=0.0, max_children=level2max_children[-1]) ename2treeNode["ROOT"] = rootNode for children in node[2]: newNode = TreeNode(parent=rootNode, level=0, eid=ename2eid[children], ename=children, isUserProvided=True, confidence_score=0.0, max_children=level2max_children[0]) ename2treeNode[children] = newNode rootNode.addChildren([newNode]) else: ename = node[0] eid = ename2eid[ ename] # assume user supervision is an entity mention in entity2id.txt level = node[1] childrens = node[2] if ename in ename2treeNode: # existing node parent_treeNode = ename2treeNode[ename] for children in childrens: newNode = TreeNode( parent=parent_treeNode, level=parent_treeNode.level + 1, eid=ename2eid[children], ename=children, isUserProvided=True, confidence_score=0.0, max_children=level2max_children[parent_treeNode.level + 1]) ename2treeNode[children] = newNode parent_treeNode.addChildren([newNode]) level2reference_edges[parent_treeNode.level].append( (parent_treeNode.eid, newNode.eid)) else: # not existing node print("[ERROR] disconnected tree node: %s" % node) return rootNode
def __init__(self, size, free_pages): # define the attributes free_pages = [x for x in range(free_pages)] self.head = TreeNode(node_left=None, node_right=None, size=size, free_pages=free_pages) self.sorted_dict = SortedDict({ size: TreeNode(node_left=None, node_right=None, size=size, free_pages=[[free_pages]]) })
def stringToTreeNode(input): # Trim trailing and leading whitespaces input = input.strip() # Remove list brackets input = input[1:-1] # Split the input parts = input.split(',') queue = deque() root = parts[0] root = root.strip() root = TreeNode(int(root)) queue.append(root) index = 1 while len(queue) != 0: node = queue.popleft() if index == len(parts): break leftchild = parts[index] leftchild = leftchild.strip() index += 1 if leftchild != "null": leftchild = TreeNode(int(leftchild)) node.left = leftchild queue.append(leftchild) if index == len(parts): break rightchild = parts[index] rightchild = rightchild.strip() index += 1 if rightchild != "null": rightchild = TreeNode(int(rightchild)) node.right = rightchild queue.append(rightchild) return root
def add_node(self, value: int): """Add a new node to the binary search tree This function will add a new tree node to the correct location in the binary search tree. :param value: The integer value which will be added to the tree :return: [temp, <'right', 'left'>] or None: The tree node and sub-tree direction to insert for new server if current server tree count is maxed, otherwise None """ temp = self.__root # flag to keep searching for a spot to insert the new value searching = True while searching: if temp.get_value() is None: # if no root value exists, then initialize that value temp.set_value(value=value) self.__count += 1 searching = False elif temp.get_value() >= value: # value is less than root so move into left sub-tree if temp.get_left_node() is not None and type(temp.get_left_node()) != str: # left sub-tree has a node which is not a pointer to a server ip temp = temp.get_left_node() elif self.__count < self.__MAX_COUNT: # add a new node to the left sub-tree if the count is less than the max storage new_node = TreeNode(value=value) temp.set_left_node(new_node) self.__count += 1 searching = False else: # server ip pointer is existing or needs to be created on the left sub-tree of this node return [temp, 'left'] elif temp.get_value() < value: # value is greater than root so move into right sub-tree if temp.get_right_node() is not None and type(temp.get_right_node()) != str: # right sub-tree has a node which is not a pointer to a server ip temp = temp.get_right_node() elif self.__count < self.__MAX_COUNT: # add a new node to the right sub-tree if the count is less than the max storage new_node = TreeNode(value=value) temp.set_right_node(new_node) self.__count += 1 searching = False else: # server ip pointer is existing or needs to be created on the right sub-tree of this node return [temp, 'right']
def bst_insert_loop(root, val): while root is not None: if val > root.val: if root.right is None: root.right = TreeNode(val) return None root = root.right elif val < root.val: if root.left is None: root.left = TreeNode(val) return None root = root.left else: print('Error: Value already in tree!') print('Error: Loop finished without inserting value!')
def get_huffman_tree(frequency_lst): frequency_lst = Counter(s) pq = PriorityQueue() for char, freq in frequency_lst: pq.insert(freq, TreeNode(char)) while pq.size() > 1: freq1, node1 = pq.delete_min() freq2, node2 = pq.delete_min() internal_node = TreeNode(node1.val + node2.val, node1, node2) pq.insert(freq1 + freq2, internal_node) _, root = pq.delete_min() return get_code(root)
def convert(self, tokens): stack = [] for token in tokens: if token in self.OPERANDS: operands_count = self.OPERANDS.get(token) node = TreeNode(token) if operands_count == 1: node.left = stack.pop() else: node.right = stack.pop() node.left = stack.pop() stack.append(node) else: stack.append(TreeNode(token)) return node
def build_tree(stix_objects, log): """ Build a multi-root tree using the stix_objects input :param stix_objects: list of stix objects :param log: :return: multi-root tree """ tree = None # # Find the first SDO to init a tree # for obj in stix_objects: if obj["type"] != "relationship" and obj["type"] != "sighting": tree = MultiRootTree(TreeNode().init_with_object(obj)) break if tree is None: log.error("Failed to start up a tree.") return None while handle_relations(stix_objects, tree, log): pass handle_sightings(stix_objects, tree, log) return tree
def extract_object(stix_objects, multi_root_tree, object_id, log): """ For a given object id, look for the node from the multi-root tree. If found, return a copy of it. If not found, look for the stix object from the stix_objects list, and creat a node for it. Return the node. :param stix_objects: stix object list :param multi_root_tree: the multi-root tree :param object_id: object id :param log: :return: """ node = None existing_node = False # # try the multi_root_tree first # visitor = GetNodeVisitor(object_id) multi_root_tree.accept(visitor) if visitor.node: node = visitor.node # A node already exists in the tree existing_node = True else: # Now look for it from the stix objects for obj in stix_objects: if obj["id"] == object_id: node = TreeNode().init_with_object(obj, log) stix_objects.remove(obj) break if not node: log.error("{} can not be found in objects or the tree".format(object_id)) return existing_node, node
def fit(self, attribute_list, class_list, row_sampler, col_sampler, bin_structure): # when we start to fit a tree, we first conduct row and column sampling col_sampler.shuffle() row_sampler.shuffle() class_list.sampling(row_sampler.row_mask) # then we create the root node, initialize histogram(Gradient sum and Hessian sum) root_node = TreeNode(name=1, depth=1, feature_dim=attribute_list.feature_dim) root_node.Grad_setter(class_list.grad.sum()) root_node.Hess_setter(class_list.hess.sum()) self.root = root_node # every time a new node is created, we put it into self.name_to_node self.name_to_node[root_node.name] = root_node # put it into the alive_node, and fill the class_list, all data are assigned to root node initially self.alive_nodes.append(root_node) for i in range(class_list.dataset_size): class_list.corresponding_tree_node[i] = root_node # then build the tree util there is no alive tree_node to split self.build(attribute_list, class_list, col_sampler, bin_structure) self.clean_up()
def parseQuery(result): all_nodes = [] stack = [] for i, res in enumerate(result): line = res[0] val = getNumOfPrecedingSpaces(line) # signals the start of an operator if i == 0 or '->' in line: op, description = getOperatorFromLine(line) node = TreeNode(op, val, description) while len(stack) > 0 and stack[-1].val >= val: stack.pop() if len(stack) > 0: # assign res[0] as a child of stack[-1] stack[-1].addChild(node) all_nodes.append(node) stack.append(node) # if the line is not an operator, it belongs as a description of the previous operator else: stack[-1].description += '\n' line = line.replace(':', '') #pydot doesn't print out semicolons stack[-1].description += line[val:] return all_nodes