def test_rightSideView(self): s = LeetSolution() self.assertEqual([], s.rightSideView(None)) root = TreeNode.makeTree([1, 2, 3, '#', 5, '#', 4]) self.assertEqual([1, 3, 4], s.rightSideView(root)) root = TreeNode.makeTree([1, 2, 3, '#', 5, '#', 4, 6]) self.assertEqual([1, 3, 4, 6], s.rightSideView(root))
def construct(l): if l is None or 0 == len(l): return None node = TreeNode(l[0]) node.left = construct([i for i in l if i < node.val]) node.right = construct([i for i in l if node.val < i]) return node
def build(self, inorder, postorder, startIndexInorder, endIndexInorder, startIndexPostorder, endIndexPostorder): if len(inorder) == 0 or len(inorder) != len(postorder) or startIndexInorder > endIndexInorder or startIndexPostorder > endIndexPostorder: return None # key concept to understand is, when reaching root of inorder, # count of all left children are the same as postorder rootNum = postorder[endIndexPostorder] count = 0 while startIndexInorder + count <= endIndexInorder and inorder[startIndexInorder + count] != rootNum: count += 1 # i is at root number, start copying root = TreeNode(rootNum) # @note:@memorize: here cannot use 'i - 1' as end of posterorder # eg. 2nd recursion, 'i - 1' = 1, that's for inorder # so it should be the ***count*** of how many nodes # root.left = self.build(inorder, postorder, startIndexInorder, i - 1, startIndexPostorder, i - 1) root.left = self.build(inorder, postorder, startIndexInorder, startIndexInorder + count - 1, startIndexPostorder, startIndexPostorder + count - 1) root.right = self.build(inorder, postorder, startIndexInorder + count + 1, endIndexInorder, startIndexPostorder + count, endIndexPostorder - 1) return root
def gen(l,r): if l> r: return [None] ans =[] for i in range(l,r+1): ltrees = gen(l,i-1) rtrees = gen(i+1,r) for j in range(len(ltrees)): for k in range(len(rtrees)): root = TreeNode(i) root.left = ltrees [j] root.right = rtrees [k] ans.append(root) # if ltrees != [None]: # for lt in ltrees: # root.left = lt # if rtrees != [None]: # for rt in rtrees: # root.right = rt # ans.append(root) # else: # root.right = None # ans.append(root) # else: # root.left = None # if rtrees != [None]: # for rt in rtrees: # root.right = rt # ans.append(root) # else: # root.right = None # ans.append(root) return ans
def linkNode(self, nodes, idx): if 0 == len(nodes): return None nodes[idx] = TreeNode(nodes[idx]) nodes[idx].left = self.linkNode(nodes[:idx], idx // 2) nodes[idx].right = self.linkNode(nodes[idx + 1:], (len(nodes) - idx - 1 - 1) // 2) return nodes[idx]
def test_inorder(self): root = TreeNode.makeTree([1, '#', 2, 3]) self.assertEqual([1, 3, 2], BTTraversal.inorder(root)) root = TreeNode.makeTree([1, 2, 3, 4, 5, '#', 6]) self.assertEqual([4, 2, 5, 1, 3, 6], BTTraversal.inorder(root)) root = TreeNode.makeTree([3, 1, 4, '#', 2, '#', 5, '#', '#', '#', 6]) self.assertEqual([1, 2, 3, 4, 5, 6], BTTraversal.inorder(root))
def buildTrees(self, start, end): if start > end: # @note:@memorize: should be something, [[]] or [None] # or the below for loop of left/right subtree will be skipped # return [] return [None] if start == end: # reaching single node return [TreeNode(start)] result = [] for i in range(start, end + 1): # end should be included # oneRoot = TreeNode(i) # @note: should be in inner loop leftSubtreeArray = self.buildTrees(start, i - 1) rightSubtreeArray = self.buildTrees(i + 1, end) for oneLeftSubtree in leftSubtreeArray: for oneRightSubtree in rightSubtreeArray: # @note:@memorize: should be here, every append is a brand new tree # or else, here is changing the reference for the same tree oneRoot = TreeNode(i) oneRoot.left = oneLeftSubtree oneRoot.right = oneRightSubtree result.append(oneRoot) return result
def _build_tree(self, X, y): ''' INPUT: - X: 2d numpy array - y: 1d numpy array OUTPUT: - TreeNode Recursively build the decision tree. Return the root node. ''' node = TreeNode() index, value, splits = self._choose_split_index(X, y) if index is None or len(np.unique(y)) == 1: node.leaf = True node.classes = Counter(y) node.name = node.classes.most_common(1)[0][0] else: X1, y1, X2, y2 = splits node.column = index node.name = self.feature_names[index] node.value = value node.categorical = self.categorical[index] node.left = self._build_tree(X1, y1) node.right = self._build_tree(X2, y2) return node
def importJSONbusiness(dataFile): """ parameters: dataFile - name of file containing business JSON objects returns: busData - list containing dictionaries representing Yelp businesses """ busData = [] rootNode = 0 try: bus = open(dataFile) except IOError: print "Unable to open data file: ", dataFile return -1 for line in bus: try: data = json.loads(line) except ValueError: print "Failed to convert JSON object to dictionary" return -1 n = TreeNode() n.key = data["business_id"] n.value = data busData.append(n) if rootNode == 0: rootNode = n else: rootNode.insert(n) return (busData, rootNode)
def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if len(inorder) == 0 or len(inorder) != len(postorder): return None print 'inorder: ', inorder print 'postorder: ', postorder # key concept to understand is, when reaching root of inorder, # count of all left children are the same as postorder rootNum = postorder[-1] i = 0 while i < len(inorder) and inorder[i] != rootNum: i += 1 # i is at root number, start copying root = TreeNode(rootNum) root.left = self.buildTree(copy.deepcopy(inorder[0: i]), copy.deepcopy(postorder[0: i])) # @note:@memorize: here is the key, need to skip root node: # for inorder, it's list[i], so 2 halves: [0:i] and [i+1:] # for postorder, it's list[-1], so 2 halves: [0:i] and [i: -1] # root.right = self.buildTree(copy.deepcopy(inorder[i + 1: ]), copy.deepcopy(postorder[i + 1: ])) root.right = self.buildTree(copy.deepcopy(inorder[i + 1: ]), copy.deepcopy(postorder[i: -1])) return root
def sortedArrayToBSTRecur(self, nums): if nums is None or 0 == len(nums): return None mid = len(nums) // 2 node = TreeNode(nums[mid]) node.left = self.sortedArrayToBSTRecur(nums[:mid]) node.right = self.sortedArrayToBSTRecur(nums[mid + 1:]) return node
def sortedArrayToBST(self, nums): if not nums: return None mid = len(nums) / 2 root = TreeNode(nums[mid]) root.left = self.sortedArrayToBST(nums[:mid]) root.right = self.sortedArrayToBST(nums[mid+1:]) return root
def doit(): val = next(vals) if val == "#": return None node = TreeNode(int(val)) node.left = doit() node.right = doit() return node
def main(): s = Solution() root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.right = TreeNode(5) result = s.binaryTreePaths(root) print result
def sortedArrayToBST(self, array): length = len(array) if length == 0: return None if length == 1: return TreeNode(array[0]) root = TreeNode(array[length / 2]) root.left = self.sortedArrayToBST(array[:length / 2]) root.right = self.sortedArrayToBST(array[length / 2 + 1:]) return root
def test_preorder(self): self.assertEqual([], BTTraversal.preorder([])) root = TreeNode.makeTree([1, '#', 2, 3]) self.assertEqual([1, 2, 3], BTTraversal.preorder(root)) root = TreeNode.makeTree([1, 2, 2, '#', 3, '#', 3]) self.assertEqual([1, 2, 3, 2, 3], BTTraversal.preorder(root)) root = TreeNode.makeTree([3, 1, 2]) self.assertEqual([3, 1, 2], BTTraversal.preorder(root))
def merge(n1, n2): if n1 is None and n2 is None: return None node = TreeNode(0) node.val = n1.val if n1 else 0 node.val += n2.val if n2 else 0 node.left = merge(n1.left if n1 else None, n2.left if n2 else None) node.right = merge(n1.right if n1 else None, n2.right if n2 else None) return node
def buildTree(self, inorder, postorder): if not inorder : return None root_val = postorder[-1] root = TreeNode(root_val) root_index = inorder.index(root_val) root.left = self.buildTree(inorder[:root_index],postorder[:root_index]) root.right = self.buildTree(inorder[root_index + 1:],postorder[root_index : -1]) return root
def __buildTree(i_l, i_r, p_l, p_r): if i_l > i_r: return None root_val = postorder[p_r] root = TreeNode(root_val) root_index = inorder[i_l:i_r+1].index(root_val) root.left = __buildTree(i_l, i_l+root_index-1, p_l, p_l+root_index-1) root.right = __buildTree(i_l+root_index+1, i_r, p_l+root_index, p_r-1) return root
def sortedArrayToBST(self, num): if num == []: return None size = len(num) locate_root = int(size/2) root = TreeNode(num[locate_root]) root.left = self.sortedArrayToBST(num[:locate_root]) root.right = self.sortedArrayToBST(num[locate_root+1:]) return root
def buildTree(self, inorder, postorder): if inorder == []: return None root = TreeNode(postorder[len(postorder)-1]) length = inorder.index(postorder[len(postorder)-1]) if length != len(postorder)-1: root.right = self.buildTree(inorder[length+1:],postorder[length: len(postorder)-1]) if length > 0: root.left = self.buildTree(inorder[:length],postorder[:length]) return root
def buildNode(_inorder, _postorder): if 0 == len(_inorder) and 0 == len(_postorder): return None if 1 == len(_inorder) and 1 == len(_postorder): return TreeNode(_postorder[-1]) val = _postorder[-1] node, idx = TreeNode(val), _inorder.index(val) node.left = buildNode(_inorder[:idx], _postorder[:idx]) node.right = buildNode(_inorder[idx + 1:], _postorder[idx:-1]) return node
def buildNode(_preorder, _inorder): if 0 == len(_preorder) and 0 == len(_inorder): return None if 1 == len(_preorder) and 1 == len(_inorder): return TreeNode(_preorder[0]) val = _preorder[0] node, idx = TreeNode(val), _inorder.index(val) node.left = buildNode(_preorder[1:1 + idx], _inorder[:idx]) node.right = buildNode(_preorder[1 + idx:], _inorder[1 + idx:]) return node
def create_Children(self, parentNode, moves): parent = parentNode.access_Board() for item in moves: oldBoard = Board(True,parentNode.get_Board()) oldBoard = oldBoard.make_move(self.player_color, item[0], item[1]) minmaxvar = self.minmax_Opposite(parentNode.get_minmax()) a = random.randint(0,100) newNode = TreeNode(oldBoard, minmaxvar, a) newNode.set_move(item) parentNode.create_Child(newNode)
def buildTree(self, preorder, inorder): if preorder == []: return None root = TreeNode(preorder[0]) length = inorder.index(preorder[0]) if length != 0: root.left = self.buildTree(preorder[1:length+1],inorder[:length]) if len(preorder) > length: root.right = self.buildTree(preorder[length+1:],inorder[length+1:]) return root
def buildTree(self, preorder, inorder): if len(preorder) == 0: return root = TreeNode(preorder[0]) left_num = inorder.index(preorder[0]) right_num = inorder.index(preorder[0])+1 root.left = self.buildTree(preorder[1:left_num+1], inorder[:left_num]) root.right = self.buildTree(preorder[right_num:], inorder[right_num:]) return root
def test002(self): s = Solution() root = TreeNode('root') nodeR = TreeNode('nodeR') root.right = nodeR n = s.maxDepth(root) print "input:\t", root print "expect:\t", 2 print "output:\t", n
def buildTreeRec(self, preorder, inorder, P, I, element): if element == 0: return None root = TreeNode(preorder[P]) div = 0; for i in range(I, I + element): if inorder[i] == preorder[P]: break div += 1 root.down = self.buildTreeRec(preorder, inorder, P + 1, I, div) root.right = self.buildTreeRec(preorder, inorder, P + div + 1, I + div + 1, element - 1 - div) return root
def call(self): matched_identifier = self.match([TokenType.ID]) if matched_identifier is not None: node = TreeNode(matched_identifier[1]) if self.match([TokenType.LPAREN]) is not None: arguments = self.args() if arguments is not None and self.match([TokenType.RPAREN]) is not None: node.addChild(arguments) return node return None
def construct(A): if A is None or 0 == len(A): return None maxIdx, maxVal = 0, A[0] for i, a in enumerate(A): if maxVal < a: maxIdx, maxVal = i, a root = TreeNode(maxVal) root.left = construct(A[:maxIdx]) root.right = construct(A[maxIdx + 1:]) return root
def __checkUnkleIsRed__(self, node: TreeNode): unkle = node.getUnkle() if unkle is not None and unkle.isRed(): node.parent.setBlackColor() unkle.setBlackColor() grandparent = node.getGrandParent() grandparent.setRedColor() self.__checkAfterInsert__(grandparent) else: self.__checkNodeAndParentBranchAndTurn__(node)
def _add(self, node, val): if(val < node.val): if(node.left != None): self._add(node.left, val) else: node.left = TreeNode(val) else: if(node.right != None): self._add(val, node.right) else: node.right = TreeNode(val)
def buildTree(self, inorder, postorder): if inorder == []: return None root = TreeNode(postorder[len(postorder) - 1]) length = inorder.index(postorder[len(postorder) - 1]) if length != len(postorder) - 1: root.right = self.buildTree(inorder[length + 1:], postorder[length:len(postorder) - 1]) if length > 0: root.left = self.buildTree(inorder[:length], postorder[:length]) return root
def A2(mot,n): """Renvoie la liste des anagrammes stricts composes au maximum de n mots""" global dico tree = TreeNode() t = time() for word in dico: if all([c in mot for c in word]) and len(word)<=len(mot): tree.add(word)#On ajoute uniquement les mots qui nous interressent print("construction arbre :", time() - t) return tree.searchAnaCompose(list(mot), tree,maxMot = n)
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) else: if currentNode.hasRightChild(): self._insert(key, val, currentNode.rightChild) else: currentNode.rightChild = TreeNode(key, val, parent=currentNode)
def _insert(self, value, node): if value >= node._value: if node._right_child == None: node._right_child = TreeNode(value) else: self._insert(value, node._right_child) else: if node._left_child == None: node._left_child = TreeNode(value) else: self._insert(value, node._left_child)
def createTestTree(depth): ranAt1 = int(random.random() * 10) ranVal1 = random.random() * 100 head = TreeNode(ranAt1, ranVal1, None, None) if depth > 1: head.left = createTestTree(depth - 1) head.right = createTestTree(depth - 1) return head
def test(inpList, ansList): root = TreeNode.fromList(inpList) ans = TreeNode.fromList(ansList) s = Solution() s.recoverTree(root) if root != ans: print('mine') root.printTree() print('answer') ans.printTree()
def _insert(self, value, currentNode): if value < currentNode.val: if currentNode.left == None: currentNode.left = TreeNode(value) else: self._insert(value, currentNode.left) if value > currentNode.val: if currentNode.right == None: currentNode.right = TreeNode(value) else: self._insert(value, currentNode.right)
def _dfs1(root, index): if root.val > index: if root.left: _dfs1(root.left, index) else: root.left = TreeNode(index) else: if root.right: _dfs1(root.right, index) else: root.right = TreeNode(index)
def buildTree(self, postorder, inorder): if len(postorder) == 0: return None root = TreeNode(postorder[-1]) left_num = inorder.index(postorder[-1]) root.left = self.buildTree(postorder[:left_num], inorder[:left_num]) root.right = self.buildTree(postorder[left_num:-1], inorder[left_num+1:]) return root
def maximumBinaryTree(arr): if arr is None or 0 == len(arr): return None maxVal, maxIdx = arr[0], 0 for i, a in enumerate(arr): if maxVal < a: maxVal, maxIdx = a, i node = TreeNode(maxVal) node.left = maximumBinaryTree(arr[:maxIdx]) node.right = maximumBinaryTree(arr[maxIdx + 1:]) return node
def __buildTree(i_l, i_r, p_l, p_r): if i_l > i_r: return None root_val = postorder[p_r] root = TreeNode(root_val) root_index = inorder[i_l:i_r + 1].index(root_val) root.left = __buildTree(i_l, i_l + root_index - 1, p_l, p_l + root_index - 1) root.right = __buildTree(i_l + root_index + 1, i_r, p_l + root_index, p_r - 1) return root
def main(): root = TreeNode(4) root.left, root.left.left, root.left.right = TreeNode(2), TreeNode( 1), TreeNode(3) root.right, root.right.right = TreeNode(5), TreeNode(6) Solution().in_order_iterative(root) print('- ' * 50) Solution().in_order_recursive(root)
def loadFirstChildren(root, foundNodes, batchloadOn): # get immediate children # batch load nodes of each fetched edge if batchloadOn: batchLoadAttribute(root.dagnode.child_edges, "child_node") for edge in root.dagnode.child_edges: child_node = edge.child_node ctree_node = TreeNode(child_node) ctree_node.parent = root ctree_node.edge_label = edge.label root.children.append(ctree_node) foundNodes.add(child_node)
def construct(indexes): head = TreeNode(1) q = [head] for lVal, rVal in indexes: n = q.pop(0) if -1 != lVal: n.left = TreeNode(lVal) q.append(n.left) if -1 != rVal: n.right = TreeNode(rVal) q.append(n.right) return head
def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode: if not pre or not post: return None node = TreeNode(pre[0]) if len(pre) != 1: x = post.index(pre[1]) + 1 node.left = self.constructFromPrePost(pre[1:x + 1], post[0:x]) node.right = self.constructFromPrePost(pre[x + 1:], post[x:-1]) return node
def increasingBST(self, root): def inorder(node): if node: yield from inorder(node.left) yield node.val yield from inorder(node.right) ans = cur = TreeNode(None) for v in inorder(root): cur.right = TreeNode(v) cur = cur.right return ans.right
def build(beg1: int, end1: int, beg2: int, end2: int) -> TreeNode: if beg1 == end1: return None rootVal = postorder[end2 - 1] root = TreeNode(rootVal) for shift in range(end1 - beg1): if inorder[shift + beg1] == rootVal: root.left = build(beg1, beg1 + shift, beg2, beg2 + shift) root.right = build(beg1 + shift + 1, end1, beg2 + shift, end2 - 1) return root
def createDecisionTree(dataset: list): """ 决策树构造函数 :param dataset:输入训练数据集 :return: 返回当前决策树的root结点 """ # 创建树根节点 tn = TreeNode(dataset) # 树根据数据集开始分裂 tn.divide() # 返回最后分裂完成的决策树 return tn
def buildTree(self, inorder, postorder): # Memory Limit Exceeded if not inorder or not postorder: return None root_val = postorder[-1] root = TreeNode(root_val) root_index = inorder.index(root_val) root.left = self.buildTree(inorder[:root_index], postorder[:root_index]) root.right = self.buildTree(inorder[root_index + 1:], postorder[root_index:-1]) return root
def DFS(start, end): if start > end: return None if start == end: return TreeNode(nums[start]) mid = (start + end) // 2 node = TreeNode(nums[mid]) node.left = DFS(start, mid - 1) node.right = DFS(mid + 1, end) return node
def helper(self, A, start, end): if start > end: return None mid = start + (end - start) / 2 root = TreeNode(A[mid]) left = self.helper(A, start, mid - 1) right = self.helper(A, mid + 1, end) root.left = left root.right = right return root
def exh_search(a, n, s): nodes = [] queue = Queue() node = TreeNode([0], [], 0, 0, a) queue.put(node) heapq.heappush(nodes, node) while True: u = queue.get() fr = u.v_to[-1] if u.v_to else 0 for _node in range(n): if u.cur_matr[fr][_node] != float('inf'): new_cost = u.cur_matr[fr][ _node] - s + u.cost if _node not in u.v_from else u.cur_matr[ fr][_node] + u.cost new_to = copy.deepcopy(u.v_to) new_from = copy.deepcopy(u.v_from) new_matr = copy.deepcopy(u.cur_matr) if fr != 0 or not u.v_to == []: new_from.append(u.v_to[-1]) new_matr[fr][_node] = float('inf') new_level = u.level + 1 if _node not in u.v_from else u.level - 1 new_to.append(_node) new_node = TreeNode(new_from, new_to, new_cost, new_level, new_matr) if not contain_node(nodes, new_node) and u.cost != float( 'inf') and not find_cycles(u): heapq.heappush(nodes, new_node) queue.put(new_node) if queue.empty(): break for el in nodes: if el.v_to and a[el.v_to[-1]][0] == float('inf'): el.cost = float('inf') elif el.v_to: el.cost += a[el.v_to[-1]][0] nodes.sort(key=lambda elem: elem.cost) ans_node = nodes[0] if ans_node.cost < 0: print(-ans_node.cost) ans_node.v_from.append(ans_node.v_to[-1]) ans_node.v_to.append(0) for i in range(len(ans_node.v_to)): print("{}->{}".format(ans_node.v_from[i] + 1, ans_node.v_to[i] + 1), end=" ") print() else: print("{}")
def __generateTrees(left, right): res = [] if left > right: return [None] else: for mid in xrange(left, right + 1): for left_child in __generateTrees(left, mid - 1): for right_child in __generateTrees(mid + 1, right): root = TreeNode(mid) root.left = left_child root.right = right_child res.append(root) return res
def cloneTree(self, root): # Write your code here if root is None: return None copy = TreeNode(root.val) left_copy = self.cloneTree(root.left) right_copy = self.cloneTree(root.right) copy.left = left_copy copy.right = right_copy return copy
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 _constructTree(start, end): if start > end or not inOrder: return None item = postOrder.pop() node = TreeNode(item) pos = index[item] node.right = _constructTree(pos+1, end) node.left = _constructTree(start, pos-1) return node
def generate(first, last): trees = [] for root in range(first, last + 1): lefts = generate(first, root - 1) rights = generate(root + 1, last) for left in lefts: for right in rights: node = TreeNode(root) node.left = left node.right = right trees += node, # trees.append(node) return trees or [None]