def _put(self, key, val, currentNode): """ If there's already a root node in place Compare new key with current node in tree, both subtrees, When there's no left or right child to search Install new node in this position :param key: index of list in BinarySearchTree :param val: additional info contained in a node :param currentNode: node that is currently compared to in tree :return: None """ 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.replaceNodeData(key, val, currentNode.leftChild, currentNode.rightChild) self.size -= 1
def recoverFromPreorder(S: str) -> TreeNode: # print(S) n = len(S) i = 0 while S[i] == "-": i += 1 j = i while j < n and S[j] != "-": j += 1 root = TreeNode(int(S[i: j])) if j == n: return root i = j while S[i] == "-": i += 1 d, j = i - j, i # d is depth of left child, i is start index of left child count = 0 while j < n: if S[j] != "-": if count == d: break count = 0 else: count += 1 j += 1 # j is start index of right child root.left = recoverFromPreorder(S[i: j].rstrip('-')) if j < n: # if right child exists root.right = recoverFromPreorder(S[j:]) return root
def _put(self, key, value, currentNode): """""" if key < currentNode.key: if currentNode.hasLeftChild(): self._put(key, value, currentNode.leftChild) else: currentNode.leftChild = TreeNode(key, value, parent=currentNode) self.updataBalance(currentNode.leftChild) elif key > currentNode.key: if currentNode.hasRightChild(): self._put(key, value, currentNode.rightChild) else: currentNode.rightChild = TreeNode(key, value, parent=currentNode) self.updataBalance(currentNode.rightChild) else: currentNode.replaceNodeData(key, value, left=currentNode.leftChild, right=currentNode.rightChild)
def main(): print( isSymmetric( TreeNode.make([5, 4, 1, None, 1, None, 4, 2, None, 2, None]))) # False print(isSymmetric(TreeNode.make([1, 2, 2, 3, 4, 4, 3]))) # True print(isSymmetric(TreeNode.make([1, 2, 2, None, 3, None, 3]))) # False
def _put(self, key, value, currentNode): """从树的根开始搜索,比较新的键值,如果新的键值是小于当前点。搜索左子 树,如 果新的键值是大于当前节点,搜索右子树。 当无左(或右)子树的搜索,我们发现的位置就是应该在子树中安装新节点的位置。 向树添加一个节点,在上一步发现插入对象的位置创建一个新的TreeNode。 """ if key < currentNode.key: if currentNode.hasLeftChild(): self._put(key, value, currentNode.leftChild) else: currentNode.leftChild = TreeNode(key, value, parent=currentNode) elif key > currentNode.key: if currentNode.hasRightChild(): self._put(key, value, currentNode.rightChild) else: currentNode.rightChild = TreeNode(key, value, parent=currentNode) else: currentNode.replaceNodeData(key, value, left=currentNode.leftChild, right=currentNode.rightChild)
def deserialize(self, data: str) -> TreeNode: if data == "[]": return None s = data.strip("[]").split(",") root = TreeNode(int(s[0])) bfs = deque() bfs.append(root) n, i = len(s), 1 while bfs: node = bfs.popleft() if i < n: if s[i] != "null": node.left = TreeNode(int(s[i])) bfs.append(node.left) i += 1 else: break if i < n: if s[i] != "null": node.right = TreeNode(int(s[i])) bfs.append(node.right) i += 1 else: break return root
def main(): print(hasPathSum(TreeNode.make([]), 0)) # False print( hasPathSum(TreeNode.make([3, 4, 5, 1, 2, None, None, None, None, 0]), 9)) # True print( hasPathSum( TreeNode.make( [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1]), 22))
def build(nums): if not nums: return None mid = len(nums) // 2 root_val = nums[mid] root = TreeNode(root_val) ltn = nums[0:mid] rtn = nums[mid + 1:] root.left = build(ltn) root.right = build(rtn) return root
def makeBst(array, start, end): mid = ((end - start) / 2) + start currentNode = TreeNode(array[mid], None, None) if start == end: return None if start == mid: return currentNode else: currentNode.left = makeBst(array, start, mid) currentNode.right = makeBst(array, mid + 1, end) return currentNode
def makeNode(self, training_list, unused_features, parent_gini, parent_ans): """ Creates a leaf node of the tree or runs recursively in order to creating a subtree :param training_list: A list of training examples for the given node :param unused_features: A list of unused features for this tree :param parant_gini: A GINI index of the parent node :param parent_ans: A class that is most likely to be assigned by the parent node :return: A new node :rtype: TreeNode """ chosen_features = [] for i in range(self.max_feat_select): choice = random.choice(unused_features) chosen_features.append(choice) unused_features.remove(choice) min_gini = parent_gini min_gini_elem = {} for feature in chosen_features: element = {} element["feature"] = feature element['threshold'], element['gini'], element['is_left_more_trues'], \ element['is_right_more_trues'], element['left_specimen'], \ element['right_specimen'] = self.chooseDescreteThreshold(feature, training_list) if element['gini'] <= min_gini: min_gini = element['gini'] min_gini_elem = element if 'feature' in min_gini_elem.keys(): chosen_features.remove(min_gini_elem['feature']) for feature in chosen_features: unused_features.append(feature) if min_gini < parent_gini: left_child = self.makeNode(min_gini_elem['left_specimen'], unused_features.copy(), min_gini, min_gini_elem['is_left_more_trues']) right_child = self.makeNode(min_gini_elem['right_specimen'], unused_features.copy(), min_gini, min_gini_elem['is_right_more_trues']) return TreeNode(min_gini_elem['feature'], min_gini_elem['threshold'], False, parent_ans, left_child, right_child) else: return TreeNode(None, None, True, parent_ans, None, None)
def sortedArrayToBST(nums: List[int]) -> TreeNode: if not nums: return None n = len(nums) mid = n // 2 root = TreeNode(nums[mid]) if mid > 0: root.left = sortedArrayToBST(nums[:mid]) if mid < n - 1: root.right = sortedArrayToBST(nums[mid + 1:]) return root
def buildTree(preorder: List[int], inorder: List[int]) -> TreeNode: if not preorder: return None root = TreeNode(preorder[0]) if len(preorder) == 1: return root i = inorder.index(preorder[0]) root.left = buildTree(preorder[1:1 + i], inorder[0:i]) root.right = buildTree(preorder[1 + i:], inorder[i + 1:]) return root
def build(preorder, inorder): if not preorder: return None else: root_val = preorder[0] root = TreeNode(root_val) root_val_idx = inorder.index(root_val) ltn = inorder[0:root_val_idx] rtn = inorder[root_val_idx + 1:] root.left = build(preorder[1:len(ltn) + 1], ltn) root.right = build(preorder[len(ltn) + 1:], rtn) return root
def postfixToExpressionTree(postfix): exprTreeStack = [] for e in postfix: node = TreeNode(e) if e in OPERATORS: if e == '!': node.left = exprTreeStack.pop() else: node.right = exprTreeStack.pop() node.left = exprTreeStack.pop() exprTreeStack.append(node) root = exprTreeStack.pop() return root
def buildTree(preorder: List[int], inorder: List[int]) -> TreeNode: if not preorder: return None node = TreeNode(preorder[0]) if len(preorder) == 1: return node i = inorder.index(node.val) node.left = buildTree(preorder[1:i + 1], inorder[:i]) node.right = buildTree(preorder[i + 1:], inorder[i + 1:]) return node
def postfixToExpressionTree(postfix): exprTreeStack = [] for e in postfix: node = TreeNode(e) if e in OPERATORS: if e == '!': node.left = exprTreeStack.pop() else: node.right = exprTreeStack.pop() node.left = exprTreeStack.pop() exprTreeStack.append(node) root = exprTreeStack.pop() return root
def build(io, po): if not po: return None else: root_val = po[-1] root = TreeNode(root_val) root_idx = io.index(root_val) ltn = io[0:root_idx] rtn = io[root_idx + 1:] right_po = po[-1 - 1:-1 - (len(rtn)) - 1:-1][::-1] left_po = po[-1 - (len(rtn)) - 1::-1][::-1] root.left = build(ltn, left_po) root.right = build(rtn, right_po) return root
def gensub(nums): if not nums: return [None] if len(nums) == 1: return [TreeNode(nums[-1])] nodeList = [] for i in range(len(nums)): leftArr = gensub(nums[0:i]) rightArr = gensub(nums[i + 1:]) for l in leftArr: for r in rightArr: node = TreeNode(nums[i]) node.left = l node.right = r nodeList.append(node) return nodeList
def __init__(self, X, Y): self.X_train = X self.Y_train = Y self.root_node = TreeNode(None, None, None, None, self.X_train, self.Y_train) self.features = self.get_features(self.X_train) self.tree_generate(self.root_node)
def insert(self, root, key, data): # Step 1 - Perform normal BST if not root: return TreeNode(key, data) elif key < root.val: root.left = self.insert(root.left, key, data) else: root.right = self.insert(root.right, key, data) # Step 2 - Update the height of the # ancestor node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Step 3 - Get the balance factor balance = self.getBalance(root) # Step 4 - If the node is unbalanced, # then try out the 4 cases # Case 1 - Left Left if balance > 1 and key < root.left.val: return self.rightRotate(root) # Case 2 - Right Right if balance < -1 and key > root.right.val: return self.leftRotate(root) # Case 3 - Left Right if balance > 1 and key > root.left.val: root.left = self.leftRotate(root.left) return self.rightRotate(root) # Case 4 - Right Left if balance < -1 and key < root.right.val: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root
def __init__(self, initial_node, goal = (0,1,2,3,4,5,6,7,8)): self.initial_node = TreeNode(initial_node) self.goal = goal self.result = {} self.time = 0 self.max_ram = 0 self.node_expand = 0 self.max_depth = 0
def _put(self, key, val, currentNode): if key == currentNode.key: # 新键等于当前结点的键,修改当前结点的payload currentNode.replaceNodeData(key, val, currentNode.leftChild, currentNode.rightChild) elif key < currentNode.key: # 新键小于当前结点的键,搜索左子树 if currentNode.hasLeftChild(): self._put(key, val, currentNode.leftChild) else: # 当前结点的左结点设置为新建 currentNode.leftChild = TreeNode(key, val, parent=currentNode) self.size += 1 else: # 新键大于当前结点的键,搜索右子树 if currentNode.hasRightChild(): self._put(key, val, currentNode.rightChild) else: # 当前结点的右结点设置为新键 currentNode.rightChild = TreeNode(key, val, parent=currentNode) self.size += 1
def put(self, key, val): if self.root: # 树有根,调用私有递归辅助函数_put() self._put(key, val, self.root) else: # 没有根,创建一个新的TreeNode作为树的根 self.root = TreeNode(key, val) self.size += 1
def addManyDataBlocks(self, dataBlocks): if len(self.lstLeaves) == 1 and math.log2(len( self.lstLeaves[0])).is_integer(): newTreeRoot = self.createTree(dataBlocks, False) mainRoot = TreeNode(data=self.root.data + newTreeRoot.data, leftChild=self.root, rightChild=newTreeRoot, nodeSide='Root') self.root.nodeSide = 'L' self.root.parentNode = mainRoot newTreeRoot.nodeSide = 'R' newTreeRoot.parentNode = mainRoot self.root = self.root.parentNode self.combineSimilarSubTrees() else: for data in dataBlocks: self.addOneBlock(data) if len(self.lstLeaves) == 1: remainingDataIndex = dataBlocks.index(data) remainingDataBlocks = dataBlocks[remainingDataIndex + 1:] if len(remainingDataBlocks) > 0: newTreeRoot = self.createTree(remainingDataBlocks, False) mainRoot = TreeNode(data=self.root.data + newTreeRoot.data, leftChild=self.root, rightChild=newTreeRoot, nodeSide='Root') self.root.nodeSide = 'L' self.root.parentNode = mainRoot newTreeRoot.nodeSide = 'R' newTreeRoot.parentNode = mainRoot self.root = self.root.parentNode self.combineSimilarSubTrees() return self.root else: return self.root return self.root
def copy_tree(root): newRoot = TreeNode() newRoot.add_node_attributes(root) if root is None: return None if root.left is not None: newRoot.add_left(copy_tree(root.left)) if root.right is not None: newRoot.add_right(copy_tree(root.right)) node_list.append(newRoot) return newRoot
def _put(self, key, val, currentNode): """ :param key: :param val: :param currentNode: :return: """ if key < currentNode.key: if currentNode.hasLeftChild(): self._put(key, val, currentNode.leftChild) else: currentNode.leftChild = TreeNode(key, val, parent=currentNode) self.updateBalance(currentNode.leftChild) else: if currentNode.hasRightChild(): self._put(key, val, currentNode.rightChild) else: currentNode.rightChild = TreeNode(key, val, parent=currentNode) self.updateBalance(currentNode.rightChild)
def setUp(self): nodes = {} for i in range(8): nodes[i] = TreeNode(i) self.root = nodes[1] nodes[1].left_child = nodes[2] nodes[1].right_child = nodes[3] nodes[2].left_child = nodes[4] nodes[2].right_child = nodes[5] nodes[3].left_child = nodes[6] nodes[3].right_child = nodes[7]
def search(self, agent, gameState, root_enemiesPos, evaluate_fun): capsules = agent.getCapsules(gameState) root_pos = gameState.getAgentState(agent.index).getPosition() root_node = TreeNode(root_pos, root_enemiesPos, capsules) root_node.value = evaluate_fun(gameState, root_node) start = time.time() q = util.Queue() q.push(root_node) closeList = {} while not q.isEmpty() and time.time() - start <= 0.95: curr_node = q.pop() curr_myPos = curr_node.myPos curr_enemiesPos = curr_node.enemiesPos curr_capsules = curr_node.capsules if curr_myPos in agent.getBorders(gameState): continue if curr_myPos in curr_capsules: curr_capsules.remove(curr_myPos) continue actions = ['North', 'South', 'East', 'West', 'Stop'] for action in actions: dx, dy = Actions.directionToVector(action) child_myPos = (curr_myPos[0]+dx, curr_myPos[1]+dy) child_depth = curr_node.depth+1 if child_myPos in gameState.data.layout.walls.asList(): continue if child_myPos not in closeList or child_depth<closeList[child_myPos]: closeList[child_myPos] = child_depth else: continue child_enemiesPos = [] for x,y in curr_enemiesPos: possibleEnemiesPos = [ (x+dx,y+dy) for (dx, dy) in [(0,1), (0,-1), (1,0), (-1,0), (0,0)] ] possibleEnemiesPos = [pos for pos in possibleEnemiesPos if pos not in gameState.data.layout.walls.asList()] nearestEnemiesPos = self.allMin([(agent.getMazeDistance(child_myPos, enemiesPos), enemiesPos) for enemiesPos in possibleEnemiesPos]) for pos in nearestEnemiesPos: if pos not in child_enemiesPos: child_enemiesPos.append(pos) child_node = TreeNode(child_myPos, child_enemiesPos, curr_capsules, curr_node) child_node.value = evaluate_fun(gameState, child_node) curr_node.childs[action] = child_node if child_node.myPos not in child_node.enemiesPos: q.push(child_node) root_node = self.backPropagation(root_node) # print agent.index, root_node.bestAction # for action in root_node.childs: # child = root_node.childs[action] # if child!=None: # print " ", action, child.value return root_node.bestAction
def put(self, key, value): """写put方法以创建二叉搜索树 检查树是否已经有根节点。如果没有,put将创建一个新 的 并把它作为树的根节点,作为子树的根。 如果一个根节点已经到位,我们就调用辅助功能_put按下列算法来搜索树""" if self.root: self._put(key, value, self.root) else: self.root = TreeNode(key, value) self.size += 1
def search_tree(self, data): node = TreeNode(data) current_node = self.root while current_node is not None: if node.data == current_node.data: print('node found') return current_node elif node.data > current_node.data: current_node = current_node.right_child elif node.data < current_node.data: current_node = current_node.left_child else: print('node not found')
def put(self, key, val): """ Builds Binary Search Tree. Checks to see if the tree has a root. If no root, creates a new TreeNode and installs it as root of tree. :param key: index of list in BinarySearchTree :param val: additional info contained in a node :return: None """ if self.root: self._put(key, val, self.root) else: self.root = TreeNode(key, val) self.size = self.size + 1
def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ l = data.split(',') if len(l) <= 1: return None curr = dummy = TreeNode(-1) stack = [curr] for i in range(0, len(l)): if l[i] == 'None': nextNode = None else: nextNode = TreeNode(l[i]) if curr: curr.left = nextNode stack.append(curr) curr = curr.left else: curr = stack.pop() curr.right = nextNode curr = curr.right return dummy.left