def build_nodes(self, parent, items, index, value): # print(items[index]) right_index = None for i in range(index, len(items)): if items[i] is not None and items[i] > value: right_index = i break if right_index is not None: right_val = items[right_index] right_node = TreeNode(right_val) parent.right = right_node items[right_index] = None self.build_nodes(right_node, items, right_index, right_val) left_index = index + 1 if left_index < len(items) and items[ left_index] is not None and items[left_index] < value: left_val = items[left_index] left_node = TreeNode(left_val) parent.left = left_node items[left_index] = None self.build_nodes(left_node, items, left_index, left_val)
def main(): inp1 = TreeNode(4) inp2 = TreeNode(5) inp1.right = inp2 inp3 = 4 print(solution(inp1, inp3))
def go_through(self, root: TreeNode): if root.left: self.go_through(root.left) new = TreeNode(root.val) if not self.result: new.right = self.result self.result = new else: self.insert_into_result(new) if root.right: self.go_through(root.right)
def constructMaximumBinaryTree(self, nums) -> TreeNode: maximum = 0 for i in range(len(nums)): if nums[i] > nums[maximum]: maximum = i root = TreeNode(nums[maximum]) left_sub = nums[:maximum] right_sub = nums[maximum + 1:] if len(left_sub) > 0: root.left = self.constructMaximumBinaryTree(left_sub) if len(right_sub) > 0: root.right = self.constructMaximumBinaryTree(right_sub) return root
def main(): inp1 = TreeNode(4) inp2 = TreeNode(5) inp3 = TreeNode(3) inp4 = TreeNode(1) inp1.right = inp2 inp3.left = inp4 print(solution(inp1, inp3))
def main(): inp1 = TreeNode(4) inp2 = TreeNode(5) inp3 = TreeNode(2) inp4 = TreeNode(6) inp1.left = inp2 inp3.right = inp4 print(solution(inp1, inp2))
def main(): inp1 = TreeNode(4) inp2 = TreeNode(2) inp3 = TreeNode(3) inp1.left = inp2 inp2.right = inp3 print(solution(inp1))
def main(): inp1 = TreeNode(1) inp2 = TreeNode(2) inp3 = TreeNode(3) inp1.left = inp2 inp2.right = inp3 inp = 6 print(solution(inp1, inp))
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> Optional[TreeNode]: result = None if t1 is None and t2 is not None: result = TreeNode(t2.val) elif t2 is None and t1 is not None: result = TreeNode(t1.val) elif t1 is not None and t2 is not None: result = TreeNode(t1.val + t2.val) else: return None l1 = t1.left if t1 is not None else None l2 = t2.left if t2 is not None else None r1 = t1.right if t1 is not None else None r2 = t2.right if t2 is not None else None result.left = self.mergeTrees(l1, l2) result.right = self.mergeTrees(r1, r2) return result
def bstFromPreorder(self, preorder) -> TreeNode: root = TreeNode(preorder[0]) self.build_nodes(root, preorder, 0, preorder[0]) return root