def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ # Solution 1 - 44 ms """ head, curr = None, root while head != root: if curr.right == head: curr.right = None if curr.left == head: curr.left = None if curr.right: curr = curr.right elif curr.left: curr = curr.left else: curr.right, head, curr = head, curr, root print_tree = PrintBinaryTree() response = print_tree.print_tree(root) print(response) """ # Solution 2 - 12 ms cur = root while cur: if cur.left: self.flatten(cur.left) left_tail = cur.left while left_tail.right: left_tail = left_tail.right old_right = cur.right cur.right = cur.left cur.left = None left_tail.right = old_right left_tail.left = None cur = old_right else: cur = cur.right print_tree = PrintBinaryTree() response = print_tree.print_tree(root) print(response)
root.left, root.right = root.right, root.left if root.left: self.invertTree(root.left) if root.right: self.invertTree(root.right) return root else: return None """ # Solution 2 - 8 ms if root: root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root # Main Call root = TreeNode(4) root.left = TreeNode(2) root.right = TreeNode(7) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right.right = TreeNode(9) root.right.left = TreeNode(6) solution = Solution() treeroot = solution.invertTree(root) # Lets print the binary tree print_tree = PrintBinaryTree() response = print_tree.print_tree(treeroot) print(response)
def helper(down, up): if self.idx >= len(preorder): return None if not down <= preorder[self.idx] <= up: return None root = TreeNode(preorder[self.idx]) self.idx += 1 root.left = helper(down, root.val) root.right = helper(root.val, up) return root self.idx = 0 return helper(-float("inf"), float("inf")) """ # Solution 2 - 48 ms return deserialize2(data) # Main call treenode = TreeNode(2) treenode.left = TreeNode(1) treenode.right = TreeNode(3) serialize = Codec() deserialize = Codec() tree = serialize.serialize(treenode) node = deserialize.deserialize(tree) # Lets print the binary tree print_tree = PrintBinaryTree() response = print_tree.print_tree(node) print(response)
break p = [] while len(stack) != 0: u = stack.pop() if u.left: p.append(u.left) if u.right: p.append(u.right) stack = p dep += 1 return root # Main Call root = TreeNode(4) root.left = TreeNode(2) root.left.left = TreeNode(3) root.left.right = TreeNode(1) root.right = TreeNode(6) root.right.left = TreeNode(5) v = 1 d = 2 solution = Solution() result = solution.addOneRow(root, v, d) # Lets print the binary tree print_tree = PrintBinaryTree() response = print_tree.print_tree(result) print(response)