Solution: Flatten Binary Tree to Linked List

This is part of a series of Leetcode solution explanations (index). If you liked this solution or found it useful, please like this post and/or upvote my solution post on Leetcode’s forums.

Leetcode Problem #114 (Medium): Flatten Binary Tr…


This content originally appeared on DEV Community and was authored by seanpgallivan

This is part of a series of Leetcode solution explanations (index). If you liked this solution or found it useful, please like this post and/or upvote my solution post on Leetcode's forums.

Leetcode Problem #114 (Medium): Flatten Binary Tree to Linked List

Description:


(Jump to: Solution Idea || Code: JavaScript | Python | Java | C++)

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.

Examples:

Example 1:
Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]
Visual: Example 1 Visual
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [0]
Output: [0]

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -100 <= Node.val <= 100

Idea:


(Jump to: Problem Description || Code: JavaScript | Python | Java | C++)

In order to properly connect the linked list, we'll need to start at the bottom and work up. This means that we'll need to move in reverse pre-order traversal order through the binary tree. Since pre-order traversal is normally "node, left, right", we'll have to move in the reverse order of "right, left, node".

Binary tree traversal is prime ground for a recursive solution, so let's define a helper (revPreOrder) for the purpose. We'll also keep a global variable head to keep track of the head of the linked list as we work our way backwards.

Per our reverse pre-order traversal approach, we want to recursively work down the right path first then the left path, if they exist. Once we've flattened the left and right paths recursively, head should at this point be equal to the next node after the current one, so we should set it as node.right. We shouldn't forget to set node.left to null, as well.

Once we're done with the current node, we can update head to node and allow the recursion to complete and move back up to the next layer. Once the recursion stack is exhausted, head will be equal to root again.

Lastly, we have to deal with an edge case of an empty root, so we can just make sure to only call the initial recursion on root if root actually is a node. There is no need for a return statement, because the test suite will evaluate root directly.

  • Time Complexity: O(N) where N is the number of nodes in the binary tree
  • Space Complexity: O(N) for the recursion stack, which is as long as the maximum depth of the binary tree, which can go up to N

Javascript Code:


(Jump to: Problem Description || Solution Idea)

var flatten = function(root) {
    let head = null
    const revPreOrder = node => {
        if (node.right) revPreOrder(node.right)
        if (node.left) revPreOrder(node.left)
        node.left = null, node.right = head, head = node
    }
    if (root) revPreOrder(root)
};

Python Code:


(Jump to: Problem Description || Solution Idea)

class Solution:
    head = None
    def flatten(self, root: TreeNode) -> None:
        def revPreOrder(node: TreeNode) -> None:
            if node.right: revPreOrder(node.right)
            if node.left: revPreOrder(node.left)
            node.left, node.right, self.head = None, self.head, node
        if root: revPreOrder(root)

Java Code:


(Jump to: Problem Description || Solution Idea)

class Solution {
    TreeNode head = null;
    public void flatten(TreeNode root) {
        if (root != null) revPreOrder(root);
    }
    private void revPreOrder(TreeNode node) {
        if (node.right != null) revPreOrder(node.right);
        if (node.left != null) revPreOrder(node.left);
        node.left = null;
        node.right = head;
        head = node;
    }
}

C++ Code:


(Jump to: Problem Description || Solution Idea)

class Solution {
public:
    void flatten(TreeNode* root) {
        if (root) revPreOrder(root);
    }
private:
    TreeNode* head = nullptr;
    void revPreOrder(TreeNode* node) {
        if (node->right) revPreOrder(node->right);
        if (node->left) revPreOrder(node->left);
        node->left = nullptr, node->right = head, head = node;
    }
};


This content originally appeared on DEV Community and was authored by seanpgallivan


Print Share Comment Cite Upload Translate Updates
APA

seanpgallivan | Sciencx (2021-05-14T08:49:02+00:00) Solution: Flatten Binary Tree to Linked List. Retrieved from https://www.scien.cx/2021/05/14/solution-flatten-binary-tree-to-linked-list/

MLA
" » Solution: Flatten Binary Tree to Linked List." seanpgallivan | Sciencx - Friday May 14, 2021, https://www.scien.cx/2021/05/14/solution-flatten-binary-tree-to-linked-list/
HARVARD
seanpgallivan | Sciencx Friday May 14, 2021 » Solution: Flatten Binary Tree to Linked List., viewed ,<https://www.scien.cx/2021/05/14/solution-flatten-binary-tree-to-linked-list/>
VANCOUVER
seanpgallivan | Sciencx - » Solution: Flatten Binary Tree to Linked List. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/14/solution-flatten-binary-tree-to-linked-list/
CHICAGO
" » Solution: Flatten Binary Tree to Linked List." seanpgallivan | Sciencx - Accessed . https://www.scien.cx/2021/05/14/solution-flatten-binary-tree-to-linked-list/
IEEE
" » Solution: Flatten Binary Tree to Linked List." seanpgallivan | Sciencx [Online]. Available: https://www.scien.cx/2021/05/14/solution-flatten-binary-tree-to-linked-list/. [Accessed: ]
rf:citation
» Solution: Flatten Binary Tree to Linked List | seanpgallivan | Sciencx | https://www.scien.cx/2021/05/14/solution-flatten-binary-tree-to-linked-list/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.