def util(start: int, end: int) -> TreeNode: if end < start: return None mid = (start + end) // 2 root = TreeNode(array[mid]) root.left = util(start, mid - 1) root.right = util(mid + 1, end) return root
def util(left, right) -> TreeNode: if left > right: return None value = preorder.pop(0) head = TreeNode(value) head.left = util(left, inorder_value_index_map[value] - 1) head.right = util(inorder_value_index_map[value] + 1, right) return head
def dfs(node: TreeNode, parent: TreeNode, is_right): if not node: return if node.value in to_delete: if parent: if is_right: parent.right = None else: parent.left = None if node.left and node.left.value not in to_delete: res.append(node.left) if node.right and node.right.value not in to_delete: res.append(node.right) dfs(node.left, node, False) dfs(node.right, node, True)
def run(): tree = TreeNode(1) tree.right = TreeNode(2) tree.right.left = TreeNode(3) tree.right.left.left = TreeNode(4) tree.right.left.left.right = TreeNode(7) tree.right.left.left.left = TreeNode(5) print_tree(tree) forest = Solution().delNodes(tree, [5, 3]) # [1, 4] for tree in forest: print() print_tree(tree)
self.dfs(root) return sorted(self.temp, key=lambda x: x.value) == self.temp def dfs(self, node: TreeNode): if node.left: self.dfs(node.left) self.temp.append(node) if node.right: self.dfs(node.right) s = Solution() a6 = TreeNode(10) a5 = TreeNode(41) a4 = TreeNode(35, a6, a5) a3 = TreeNode(20) a2 = TreeNode(30, a3, a4) a1 = TreeNode(40, a2) b6 = TreeNode(34) b5 = TreeNode(36) b4 = TreeNode(35, b6, b5) b3 = TreeNode(20) b2 = TreeNode(30, b3, b4) b1 = TreeNode(40, b2) print_tree(a1) print(s.isValidBST_list(a1))
def run(): root = TreeNode( 50, TreeNode(40, TreeNode(30, TreeNode(20), TreeNode(35)), TreeNode(45, TreeNode(44), TreeNode(46))), TreeNode(55, TreeNode(52, TreeNode(51), TreeNode(53)), TreeNode(70, TreeNode(60), TreeNode(90))), ) print(Solution.is_binary_tree_balanced(root))
this_level.append(root) while len(this_level): next_level = [] # To make left side view, we just need to take this_level[0] instead res.append(this_level[-1].value) for n in this_level: if n.left: next_level.append(n.left) if n.right: next_level.append(n.right) this_level = next_level return res tree = TreeNode(1) tree.left = TreeNode(2) tree.left.left = TreeNode(5) tree.right = TreeNode(3) # tree.right.right = TreeNode(4) # tree.right.left = TreeNode(6) print_tree(tree) s = Solution() print(s.rightSideView(tree))
def run(): tree = TreeNode(1) tree.left = TreeNode(2) tree.left.left = TreeNode(4) tree.left.right = TreeNode(5) tree.left.left.left = TreeNode(7) tree.right = TreeNode(3) tree.right.right = TreeNode(6) tree.right.right.right = TreeNode(8) print_tree(tree) assert Solution().deepestLeavesSum(tree) == 15