root = TreeNode( TreeNode( TreeNode( TreeNode(None, None, 'O'), TreeNode( TreeNode(None, None, "Q"), TreeNode(TreeNode(TreeNode(None, None, ",")), None, "Z"), "G" ), "M" ), TreeNode( TreeNode( TreeNode(None, None, "Y"), TreeNode( TreeNode( TreeNode(None, None, "!") ), None, "C" ), "K" ), TreeNode( TreeNode(None, None, "X"), TreeNode(None, None, "B"), "D" ), "N" ), "T" ), TreeNode( TreeNode( TreeNode( TreeNode(None, None, "J"), TreeNode(None, None, "P"), "W" ), TreeNode( TreeNode(None, TreeNode(TreeNode(None, None, "."))), TreeNode(None, None, "L"), "R" ), "A" ), TreeNode( TreeNode( TreeNode( None, TreeNode(None, TreeNode(None, None, "?")) ), TreeNode(None, None, "F"), "U" ), TreeNode( TreeNode(None, None, "V"), TreeNode(None, None, "H"), "S" ), "I" ), "E" ) )
from tree import TreeNode myA = TreeNode('A') myB = TreeNode('B') myC = TreeNode('C') myD = TreeNode('D') myE = TreeNode('E') myF = TreeNode('F') myA.left = myB myA.right = myC myB.left = myD myB.right = myE myC.left = myF head = myA def countTree(head): if head == None: return 0 elif head.left == None and head.right == None: return 1 else: return countTree(head.left) + countTree(head.right) print("Terminal node number is: {}".format(countTree(head)))
from tree import TreeNode def helper(root, val): if not root: return 0 val = val * 10 + root.value if root.left is None and root.right is None: return val return helper(root.left, val) + helper(root.right, val) def sum_path(root): return helper(root, 0) if __name__ == '__main__': root = TreeNode(4) root.left = TreeNode(9) root.right = TreeNode(0) root.left.left = TreeNode(5) root.left.right = TreeNode(1) print sum_path(root)
:rtype: TreeNode """ if t1 is None: return t2 if t2 is None: return t1 t1.data = t1.data + t2.data t1.left = merge_trees(t1.left, t2.left) t1.right = merge_trees(t1.right, t2.right) return t1 tree1 = TreeNode(1) tree1.insert(3) tree1.insert(2) tree1.insert(5) tree2 = TreeNode(2) tree2.insert(1) tree2.insert(3) tree2.insert(4) tree2.insert(7) print("=== Tree 1 ===") tree1.print_tree() print("=== Tree 2 ===") tree2.print_tree() print()
from tree import TreeNode, inorder maxlevel = 0 def left_view(root, level): # in a way we will be going pre # root left and right if left is null # at each level print only once global maxlevel if root: if maxlevel < level: print(root.data) maxlevel = level left_view(root.left, level + 1) left_view(root.right, level + 1) pass if __name__ == "__main__": rootNode = TreeNode(1) firstNode = TreeNode(2) secondNode = TreeNode(3) thirdNode = TreeNode(6) rootNode.left = firstNode rootNode.right = secondNode secondNode.right = thirdNode # do a traversal to show all the nodes # inorder(rootNode) #works left_view(rootNode, level=1)
def test_breadth_first_traverse_on_one_node(self): node = TreeNode('a') node.breadth_first_traverse(self.node_visitor) self.assertEqual([node], self.visited_nodes)
from tree import TreeNode from linked_list import LinkedList, print_list def tree_to_list(root): if not root: return root new_head = head = LinkedList(root.value) right = tree_to_list(root.right) head.next = tree_to_list(root.left) while head.next: head = head.next head.next = right return new_head if __name__ == '__main__': root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(5) root.left.left = TreeNode(3) root.left.right = TreeNode(4) root.right.right = TreeNode(6) print_list(tree_to_list(root))
def is_pl(formula, root, symbols): current_root = root if formula == "": return False # empty formula not allowed if is_valid_id(formula) or is_falsum(formula): current_root.left_child = TreeNode(formula) current_root.left_child.is_leaf = True if formula not in symbols: symbols.append(formula) return True # this covers all formulae that consist of a single symbol if formula[0] != '(' or formula[len(formula) - 1] != ')': return False # this takes care of missing braces around longer statements for i in range(0, len(formula)): # if '(' was read, create new child of current root node. if formula[i] == '(': if current_root.left_child is None: current_root.is_operator = True current_root.left_child = TreeNode() temp = current_root current_root = current_root.left_child current_root.parent = temp elif current_root.right_child is None: current_root.is_operator = True current_root.right_child = TreeNode() temp = current_root current_root = current_root.right_child current_root.parent = temp else: # we found ( too much return False elif formula[i] == ')': # when ')' is read go to the next higher level in tree if current_root == root: return False if current_root.left_child is None or current_root.right_child is None: # something is wrong return False if not current_root.left_child.has_ancestor_leaf or not current_root.right_child.has_ancestor_leaf: # if we are here, one of the child nodes has no path to a leaf. That is bad return False if current_root.has_ancestor_leaf: current_root.parent.has_ancestor_leaf = True current_root = current_root.parent elif is_valid_id(formula[i]) or is_falsum(formula[i]): if formula[i] not in symbols: symbols.append(formula[i]) if current_root.is_leaf: return False # This means that there are more than 1 letter/symbol # add a new left or right child and assign the symbol if current_root.left_child is None: current_root.left_child = TreeNode(formula[i]) current_root.left_child.is_leaf = True current_root.left_child.has_ancestor_leaf = True elif current_root.right_child is None: current_root.right_child = TreeNode(formula[i]) current_root.right_child.is_leaf = True current_root.right_child.has_ancestor_leaf = True else: return False current_root.is_operator = True current_root.has_ancestor_leaf = True elif formula[i] == '>': # we found an implication if current_root.is_leaf: # something is wrong. return False if current_root.left_child is None: # read an operator without left side return False if not current_root.left_child.has_ancestor_leaf and not current_root.left_child.is_leaf: # left side is not valid for reading implication return False i += 1 continue else: return False if current_root == root: return True # if we were able to build the tree and the last closing brace brought us back to root, # the formula is valid # else, it is not. return False
from tree import TreeNode, serialize import sys node_01 = TreeNode('A', 1) node_02 = TreeNode('X', 2) node_03 = TreeNode('H', 3) node_04 = TreeNode('G', 4) node_05 = TreeNode('E', 5) node_06 = TreeNode('G', 6) node_07 = TreeNode('E', 7) node_08 = TreeNode('H', 8) node_09 = TreeNode('A', 9) node_10 = TreeNode('B', 10) node_11 = TreeNode('C', 11) node_12 = TreeNode('H', 12) node_13 = TreeNode('A', 13) node_14 = TreeNode('C', 14) node_15 = TreeNode('B', 15) node_16 = TreeNode('E', 16) node_17 = TreeNode('E', 17) node_18 = TreeNode('E', 18) node_19 = TreeNode('E', 19) node_20 = TreeNode('A', 20) node_21 = TreeNode('B', 21) node_22 = TreeNode('C', 22) node_23 = TreeNode('A', 23) node_24 = TreeNode('B', 24) node_25 = TreeNode('C', 25) node_26 = TreeNode('D', 26) node_27 = TreeNode('A', 27) node_28 = TreeNode('B', 28)
else: invalid_input = True break if invalid_input: print('Invalid input!') continue calc.set_infix_string(user_input) postfix = calc.get_postfix_notation() memory = [] i = 0 while len(postfix) > i: current = postfix[i] if current in operators_set: node = TreeNode(current) child2 = memory.pop() child1 = memory.pop() child1.set_parent(node) child2.set_parent(node) node.add_child(child1) node.add_child(child2) memory.append(node) else: node = TreeNode(current) memory.append(node) i += 1 tree = Tree('0') tree.root = memory.pop() print(tree.root) print('result:', calc.calculate())
def _TreeGenerate(self, D, A, v=None, depth=0): """Generate a decision tree. Note that all data vectors are Lists. Args: D (Tuple[x, y]): x is feature vectors and y is label vectors. A (List[Tuple(name, type)]): arrtributes index list. """ root = TreeNode() root.set_value(v) X, y = D # all the samples belong to the same class if len(set(y)) == 1: root.set_label(y[0]) return root # A is empty set or all the samples are the same on arrtributes set A or achieving the maximum depth if len(A) == 0 or ID3DecisionTree._is_same(X) or ( self.max_depth > 0 and depth + 1 > self.max_depth): most_common_class = Counter(y).most_common(1)[0][0] root.set_label(most_common_class) return root # get the optimal spliting attribute optimal_attribute_idx, optimal_point = self._get_optimal_attribute_idx( D, A) buf_v = dict() for index, sample in enumerate(X): v = sample[optimal_attribute_idx] if A[optimal_attribute_idx][1] != "CONTINUOUS": if v not in buf_v: buf_v[v] = [[], []] buf_v[v][0].append(sample[:optimal_attribute_idx] + sample[optimal_attribute_idx + 1:]) buf_v[v][1].append(y[index]) else: if "pos" not in buf_v: buf_v["pos"] = [[], []] buf_v["neg"] = [[], []] if v <= optimal_point: buf_v["neg"][0].append(sample[:optimal_attribute_idx] + sample[optimal_attribute_idx + 1:]) buf_v["neg"][1].append(y[index]) else: buf_v["pos"][0].append(sample[:optimal_attribute_idx] + sample[optimal_attribute_idx + 1:]) buf_v["pos"][1].append(y[index]) # set the optimal attribute for root root.set_attr(A[optimal_attribute_idx][0]) root.set_attr_idx(self.attr2idx[A[optimal_attribute_idx][0]]) new_A = A[:optimal_attribute_idx] + A[optimal_attribute_idx + 1:] for v in buf_v: D_v = tuple(buf_v[v]) if A[optimal_attribute_idx][1] != "CONTINUOUS": if D_v[0]: root.add_child(self._TreeGenerate(D_v, new_A, v, depth + 1)) else: if D_v[0]: if v == "pos": root.add_child( self._TreeGenerate(D_v, new_A, (">", optimal_point), depth + 1)) else: root.add_child( self._TreeGenerate(D_v, new_A, ("<", optimal_point), depth + 1)) return root
from tree import TreeNode # Tree 1 mA = TreeNode('A') mB = TreeNode('B') mC = TreeNode('C') mD = TreeNode('D') mE = TreeNode('E') mF = TreeNode('F') mA.left = mB mA.right = mC mB.left = mD mB.right = mE mC.left = mF mhead = mA # Tree 2 nA = TreeNode('A') nB = TreeNode('B') nC = TreeNode('C') nD = TreeNode('D') nE = TreeNode('E') nF = TreeNode('F') nA.left = nB nA.right = nC nB.left = nD nB.right = nE nC.right = nF
# set which implementation to execute test = "diameter" if test == "diameter": import diameter from tree import TreeNode if test == "flatten": from TreeNode import TreeNode import traverse_tree import flatten if __name__ == "__main__": if test == "diameter": root = TreeNode(5) root.left = TreeNode(2) root.right = TreeNode(7) root.left.right = TreeNode(3) root.right.left = TreeNode(6) root.right.right = TreeNode(8) root.right.right.right = TreeNode(9) # sol = diameter.Solution() # print sol.getHeight(root) # print sol.getDiameter(root) # print sol.diameter(root) root.traverse_breath_first() root.traverse_pre_order() if test == "flatten": root = TreeNode(5)
from tree import TreeNode import sys def helper(root, max, min): if not root: return True if root.value > max or root.value < min: return False return helper(root.left, root.value, min) and helper( root.right, max, root.value) def validate_bst(root): return helper(root, sys.maxint, -sys.maxint - 1) if __name__ == '__main__': root = TreeNode(2) root.left = TreeNode(1) root.right = TreeNode(3) print validate_bst(root)
def assert_depth_first_traverse_on_one_node(self, function): node = TreeNode('a') function(node, self.node_visitor) self.assertEqual([node], self.visited_nodes)
def __init__(self, total_time=100): self._policy = policy_value_fn self._c_puct = 2 self._total_time = total_time self._storage = Store() self._root = TreeNode(None,1.0)
def test_size_of_one_node(self): node = TreeNode('a') self.assertEqual(1, node.size)
def main(): root = TreeNode("Electronics") laptop = TreeNode("Laptop") laptop.add_child(TreeNode("Mac")) laptop.add_child(TreeNode("Surface")) laptop.add_child(TreeNode("Thinkpad")) cellphone = TreeNode("Cell Phone") cellphone.add_child(TreeNode("iPhone")) cellphone.add_child(TreeNode("Google Pixel")) cellphone.add_child(TreeNode("Vivo")) tv = TreeNode("TV") tv.add_child(TreeNode("Samsung")) tv.add_child(TreeNode("LG")) root.add_child(laptop) root.add_child(cellphone) root.add_child(tv) root.print_tree()
def test_breadth_first_traverse_gen_on_one_node(self): node = TreeNode('a') generated_nodes = [n for n in node.breadth_first_traverse_gen()] self.assertEqual([node], generated_nodes)
from tree import TreeNode class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ root = TreeNode(3) a1 = TreeNode(9) b1 = TreeNode(20) a2 = TreeNode(15) b2 = TreeNode(7) root.left = a1 root.right = b1 b1.left = a2 b1.right = b2
def helper(root, t, k, res): if not root: return helper(root.left, t, k, res) if len(res) < k: res.append(root.value) else: if abs(root.value - t) < abs(res[0] - t): del res[0] res.append(root.value) helper(root.right, t, k, res) def closest(root, t, k): res = [] helper(root, t, k, res) return res if __name__ == '__main__': root = TreeNode(10) root.left = TreeNode(5) root.right = TreeNode(30) root.left.left = TreeNode(1) root.left.right = TreeNode(6) root.right.left = TreeNode(29) root.right.right = TreeNode(100) t = 25 k = 3 print closest(root, t, k)
def test_str_node_without_parent(self): node = TreeNode('a') self.assertEqual('a', str(node))
#read the input parameters no_cases = args.size noise_probability = args.noise tree_folder = args.i record_timestamps = args.t format_log = args.f #specify the folder with the trees tree_files = glob.glob(tree_folder + "*.nw") #for each tree for filepath in tree_files: #generate traces t = TreeNode(filepath,format=1) if t.get_tree_root().name == 'choice': traces = [] children = t.get_children() for i in range(no_cases): child = select_child(children) if child.is_leaf(): artificial_parent = TreeNode('sequence:1;') artificial_parent.add_child(child=child) simulator = TraceSimulator(artificial_parent.write(format=1,format_root_node=True), record_timestamps) else: simulator = TraceSimulator(child.write(format=1,format_root_node=True), record_timestamps) traces.append(simulator.case.trace)
def test_str_node_with_parent(self): root = TreeNode('a') node = root.add_child('b') self.assertEqual('a', str(root)) self.assertEqual('b', str(node))
l = subtree(root.left) r = subtree(root.right) if l is False or r is False: return False if root.left and root.value != root.left.value: return False if root.right and root.value != root.right.value: return False subtree.count += 1 return True def print_tree(root): if root is None: return print root.value print_tree(root.left) print_tree(root.right) if __name__ == '__main__': root = TreeNode(5) root.left = TreeNode(1) root.right = TreeNode(5) root.left.left = TreeNode(5) root.left.right = TreeNode(5) root.right.right = TreeNode(5) subtree.count = 0 subtree(root) print subtree.count
def test_repr_node_without_parent(self): node = TreeNode('a') self.assertEqual('[key=a, parent=None, children=[]]', repr(node))
from tree import TreeNode import sys def max_path_sum(root): helper.res = -sys.maxint - 1 helper(root) return helper.res def helper(root): if not root: return 0 max_left = helper(root.left) max_right = helper(root.right) single_max = max(max(max_left, max_right) + root.value, root.value) total_max = max(single_max, max_left + max_right + root.value) helper.res = max(helper.res, total_max) return single_max if __name__ == '__main__': root = TreeNode(-10) root.left = TreeNode(9) root.right = TreeNode(20) root.right.left = TreeNode(15) root.right.right = TreeNode(7) print max_path_sum(root)
def test_height_of_one_node(self): node = TreeNode('a') self.assertEqual(0, node.height)
for node in level: if node.left is None and node.right is None: return height if node.left is not None: new_level.append(node.left) if node.right is not None: new_level.append(node.right) level = new_level return height def print_tree(root): if root is not None: print(root.val) print_tree(root.left) print_tree(root.right) if __name__ == "__main__": tree = TreeNode(10) tree.left = TreeNode(12) tree.right = TreeNode(15) tree.left.left = TreeNode(25) tree.left.left.right = TreeNode(100) tree.left.right = TreeNode(30) tree.right.left = TreeNode(36) height = min_height(tree) print_tree(tree) print("height:", height)
def qlearn2(resume=True): root_state = State(ACTORS, PLACES, ITEMS) root_node = TreeNode(state=root_state, parent_edge=None, possible_methods=True) from tree import POSSIBLE_METHODS num_methods = len(POSSIBLE_METHODS) table2 = {} eps = 0.2 if resume: with open("table2.pickle", "rb") as table2file: table2 = pickle.load(table2file) current_node = root_node edge = None depth = 0 counter = 0 while True: if depth >= 20: depth = 0 counter += 1 edge = None #print() if counter % 100 == 0: print("Counter - " + str(counter) + " - Dumping To File") with open("table2.pickle", "wb") as table2file: pickle.dump(table2, table2file, protocol=pickle.HIGHEST_PROTOCOL) if counter % 2000 == 0: print("Tree destroyed") root_state = State(ACTORS, PLACES, ITEMS) root_node = TreeNode(state=root_state, parent_edge=None, possible_methods=True) current_node = root_node if eps > 0.2: eps *= 0.97 continue if not current_node.edges: expand_all_believable_edges(node=current_node, debug=True) next_edge = choose_q_edge(node=current_node, epsilon=eps) best_edge = choose_max_q_edge(node=current_node) if edge != None: reward = percent_goals_satisfied(current_node, GOALS) idx = state_index_number_2(edge.prev_node.state) if idx not in table2: table2[idx] = [0.1] * num_methods idxc = state_index_number_2(current_node.state) if idxc not in table2: table2[idxc] = [0.1] * num_methods #print(idxc) #print(idx) #print(len(POSSIBLE_METHODS)) bestqval = table2[idxc][find_edge_index(best_edge)] qval = table2[idx][find_edge_index(edge)] table2[idx][find_edge_index( edge)] = qval + 0.1 * (reward + 0.9 * (bestqval) - qval) #print("{} {} {}".format(edge.method.sentence, reward, edge.qval)) edge = next_edge depth += 1 current_node = edge.next_node