Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode() {
this.val = 0;
this.left = null;
this.right = null;
}

TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}

TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}

public class FlattenBinaryTree {

// Function to flatten the tree into linked list (preorder)
public static void flatten(TreeNode root) {
if (root == null) return;

java.util.Stack<TreeNode> stack = new java.util.Stack<>();
stack.push(root);

while (!stack.isEmpty()) {
TreeNode current = stack.pop();

// Push right child first (so left is processed first)
if (current.right != null)
stack.push(current.right);

if (current.left != null)
stack.push(current.left);

// Connect current node to next node in preorder
if (!stack.isEmpty())
current.right = stack.peek();

current.left = null; // Set left child to null
}
}

// Helper function to print the flattened tree
public static void printFlattened(TreeNode root) {
TreeNode curr = root;
while (curr != null) {
System.out.print(curr.val);
if (curr.right != null)
System.out.print(" -> ");
curr = curr.right;
}
System.out.println();
}

public static void main(String[] args) {
// Construct the tree:
// 1
// / \
// 2 5
// / \ \
// 3 4 6

TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(5);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(4);
root.right.right = new TreeNode(6);

System.out.println("Before Flattening (Tree created)");

flatten(root);

System.out.println("\nFlattened Linked List:");
printFlattened(root);
}
}
69 changes: 69 additions & 0 deletions Linked Lists/Flatten Binary Tree to Linked List/Markdown.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Flatten Binary Tree to Linked List

### Description
You are given the root of a binary tree.
Flatten the tree into a “linked list” in-place following the preorder traversal (Root → Left → Right).

After flattening,

- Each node’s right child points to the next node in preorder traversal.

- Each node’s left child is set to null.

**Example:**
Input:
1
/ \
2 5
/ \ \
3 4 6

Output:
1 -> 2 -> 3 -> 4 -> 5 -> 6


---

## Approach 1: Using Stack (Iterative Preorder)

**Concept:**

- Use a stack to perform a preorder traversal of the binary tree.
- Push the right subtree first and then the left subtree (so left is processed first).
- Set each node’s right pointer to the next node in preorder order.
- Set each node’s left pointer to null.

**Algorithm:**

1. Initialize a stack and push the root node.
2. While the stack is not empty:
- Pop the top node as current.
- If current.right exists, push it onto the stack.
- If current.left exists, push it onto the stack.
- If the stack is not empty, set current.right to the top of the stack.
- Set current.left = null.
3. The tree is now flattened.

**Complexity:**

- Time: `O(N)`
- Space: `O(N)`

---

## Approach 2: Optimized (Morris Traversal - O(1) Space)

**Concept:**

- Traverse the tree using preorder traversal without extra space.
- For each node:
- If it has a left subtree:
- Find the rightmost node in its left subtree.
- Connect that node’s right to the current node’s original right subtree.
- Move the left subtree to the right and set left = null.
- Move to the next right node.

**Complexity:**

- Time: `O(N)`
- Space: `O(1)` (no stack or recursion used)
72 changes: 72 additions & 0 deletions Linked Lists/Flatten Binary Tree to Linked List/flatten_tree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#include <bits/stdc++.h>
using namespace std;

struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

TreeNode *root1 = nullptr;
void InorderTraversal(TreeNode *root)
{
if (root != nullptr)
{
TreeNode *newNode = new TreeNode(root->val);
if (root1 == nullptr)
{
root1 = newNode;
}
else
{
root1->right = newNode;
}
InorderTraversal(root->left);
InorderTraversal(root->right);
}
else
{
return;
}
}

void flatten(TreeNode *root)
{
// root1 = root;
if (root == nullptr)
return;
flatten(root->right);
flatten(root->left);
root->right = root1;
root->left = nullptr;
root1 = root;
}

void preorder(TreeNode* root) {
if (root == nullptr) return;
cout << root->val << " ";
preorder(root->left);
preorder(root->right);
}

int main()
{
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(5);
root->left->left = new TreeNode(3);
root->left->right = new TreeNode(4);
root->right->right = new TreeNode(6);
cout << "Original Traversal: ";
preorder(root);
cout << endl;
flatten(root);
cout << "Linked list Traversal: ";
preorder(root);
cout << endl;
return 0;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right


def flatten(root):
"""
Flattens the binary tree into a linked list in-place (preorder order).
"""
if not root:
return

# Use a stack to do preorder traversal
stack = [root]

while stack:
current = stack.pop()

# Push right first so left is processed first
if current.right:
stack.append(current.right)
if current.left:
stack.append(current.left)

# Connect current node to next node in preorder
if stack:
current.right = stack[-1]

current.left = None # set left child to None


# Helper function to print flattened tree
def printFlattened(root):
while root:
print(root.val, end=" -> " if root.right else "")
root = root.right
print()


# Driver code
if __name__ == "__main__":
# Create the tree:
# 1
# / \
# 2 5
# / \ \
# 3 4 6
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.right = TreeNode(6)

print("Before Flattening:")
print("Tree structure is now flattened below:")
flatten(root)

print("\nFlattened Linked List:")
printFlattened(root)