Flatten Binary Tree to Linked List LeetCode Solution

Flatten Binary Tree to Linked List LeetCode Solution says that – Given the root of a binary tree, flatten the tree into a “linked list”:

  • The “linked list” should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
  • The “linked list” should be in the same order as a pre-order traversal of the binary tree.

 

Example 1:

Flatten Binary Tree to Linked List LeetCode SolutionInput:

 root = [1,2,5,3,4,null,6]

Output:

 [1,null,2,null,3,null,4,null,5,null,6]

Example 2:

Input:

 root = []

Output:

 []

Example 3:

Input:

 root = [0]

Output:

 [0]

 

ALGORITHM –

IDEA –

  • In order to flatten a binary tree, we will first find the rightmost element of the left subtree and after we got the rightmost element we will link the right-pointer of that node with a right subtree of a given tree.
  • In step 2 we will link the right pointer of the root node with the left-subtree and set the left-subtree as null.
  • In step 3 now our root node is a right-subtree node same process will happen with this node and the process will still continue until all the left parts become null.

Approach for Flatten Binary Tree to Linked List Leetcode Solution –

– At first, i will run a loop i.e. while(root != null) then will take two variables and store the left-subtree.

– then will check check for the rightmost node of left-subtree by using while(k.left != null) and will link that node with right subtree using (k.right = root.right).

– then link  right pointer of root node with left subtree(root.right = left) and set left pointer of root node as null(root.left=null) and will update by ( root = root.right ) so now root is right subtree node.

– this process will continue until all left-subtree parts become right subtree. Hence, the binary tree will get flattened.

 

Flatten Binary Tree to Linked List LeetCode Solution

Flatten Binary Tree to Linked List LeetCode Solution

Python Solution:

class Solution:
    def flatten(self, root: Optional[TreeNode]) -> None:
        while(root):
            
            if root.left:
                
                k = root.left
                temp = root.left
            
            
                while(k.right):
                    k = k.right
            
                k.right = root.right
            
                root.right = temp
            
                root.left = None
            
            root = root.right

Java Solution:

class Solution {
    public void flatten(TreeNode root) {       
        while (root != null) {
            if (root.left != null) {
                TreeNode k = root.left;
                TreeNode temp = root.left;
                while (k.right != null) k = k.right;
                k.right = root.right;
                root.right = temp;
                root.left = null;
            }
            root = root.right;
        }
    }
}

Time complexity: O(N)

Space Complexity: O(1)

As we have traversed only once, time complexity will be o(n).

and as we haven’t taken any extra space, space complexity will be o(1) constant extra space.

Similar Question – https://tutorialcup.com/interview/linked-list/flattening-linked-list.htm

Insert Delete GetRandom O(1) Leetcode Solution

Problem Statement The Insert Delete GetRandom O(1) LeetCode Solution – “Insert Delete GetRandom O(1)” asks you to implement these four functions in O(1) time complexity. insert(val): Insert the val into the randomized set and return true if the element is initially absent in the set. It returns false when the …

Read more

Odd Even Linked List Leetcode Solution

Problem Statement The Odd-Even Linked List LeetCode Solution – “Odd-Even Linked List” states that given a non-empty singly linked list. We need to group all nodes with odd indices together followed by the nodes with even indices, and return the reordered list. Note that the relative order inside both the …

Read more

Add Two Numbers II Leetcode Solution

Problem Statement The Add Two Numbers II LeetCode Solution – “Add Two Numbers II” states that two non-empty linked lists represent two non-negative integers where the most significant digit comes first and each node contains exactly one digit. We need to add the two numbers and return the sum as …

Read more

Substring with Concatenation of All Words Leetcode Solution

Problem Statement The Substring with Concatenation of All Words LeetCode Solution – “Substring with Concatenation of All Words” states that given a string s and an array of string words where each word is of the same length. We need to return all starting indices of the substring that is …

Read more

Design A Leaderboard Leetcode Solution

Problem Statement The Design A Leaderboard LeetCode Solution – “Design A Leaderboard” asks you to complete 3 functions: addScore(playerId, score): Update the leaderboard by adding a score to the given player’s score. If there doesn’t exist any player, add such id on the leaderboard. top(K): Return the top sum of …

Read more

Concatenation of Array LeetCode Solution

Problem Description: The Concatenation of Array Leetcode Solution: states that Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). Specifically, ans is the concatenation of two nums arrays. Return the array ans. Let’s first try to understand the problem and what it states. The problem …

Read more

Sliding Window Median Leetcode Solution

Problem Statement The Sliding Window Median LeetCode Solution – “Sliding Window Median” states that given an integer array nums and an integer k, where k is the sliding window size. We need to return the median array of each window of size k. Example: Input: [1,3,-1,-3,5,3,6,7], k = 3 Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000] Explanation: Median …

Read more

Divide Two Integers Leetcode Solution

Problem Statement The Divide Two Integers LeetCode Solution – “Divide Two Integers” states that you’re given two integers dividend and divisor. Return the quotient after dividing the dividend by the divisor. Note that we’re assuming that we’re dealing with an environment that could store integers within a 32-bit signed integer …

Read more

Translate »