Address
304 North Cardinal St.
Dorchester Center, MA 02124
Work Hours
Monday to Friday: 7AM - 7PM
Weekend: 10AM - 5PM
Address
304 North Cardinal St.
Dorchester Center, MA 02124
Work Hours
Monday to Friday: 7AM - 7PM
Weekend: 10AM - 5PM
Now you will get it.
Recap – Function that calls itself.
How does Recursion actually solves a problem –
Let’s see how to Flatten the tree-
Input: root = [1, 2, 5, 3, 4, null, 6]
Output: [1, null, 2, null, 3, null, 4, null, 5, null, 6]
Here we need to move the left subtree to the right left in place (in the same tree) so it forms a linked list such that it maintains preorder traversal of binary tree.
Following are the 2 different code for this
Method – 1 : Top-Down Approach
# Have to modify in place
def flatten(self, root: Optional[TreeNode]) -> None:
# To keep track of previous element
prev = None
def flatten_helper(root):
nonlocal prev
if root == None:
return
right = root.right
if prev:
prev.right = root
prev.left = None
prev = root
flatten_helper(root.left)
flatten_helper(right)
return flatten_helper(root)
Below Explain it in action (Recommended speed is 1.5x)