Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flatten Binary Tree to Linked List #40

Open
kokocan12 opened this issue Jun 23, 2022 · 0 comments
Open

Flatten Binary Tree to Linked List #40

kokocan12 opened this issue Jun 23, 2022 · 0 comments

Comments

@kokocan12
Copy link
Owner

Problem

When a root node of binary tree is given, flatten the binary tree to linked list.
Linked list means that every nodes of the tree connected through the right child.
Linked list should be ordered in pre-order(head first, then left, right direction)

image

Approach

We can divide tree to three parts. (head, left, right)
image

Then, flatten left first, connect the right part to the last item of the flattened left part.

image

The code is below.

function travel(root) {
    if(root === null) return null;
    
    const tempLeft = root.left;
    const tempRight = root.right;
    root.left = null;
    root.right = travel(tempLeft);
    const rightEnd = reachToRightEnd(root);
    rightEnd.right = travel(tempRight);
    
    return root;
}

function reachToRightEnd(node) {
    if(node === null) return node;
    
    while(node.right !== null) {
        node = node.right;
    }
    
    return node;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant