Skip to content

Commit cfbaf66

Browse files
authored
Merge pull request #134 from PrakashShukla0907/add-flatten-binary-tree
Added Flatten Binary Tree algorithm in C++ under CPP/tree/
2 parents 74780b2 + 2f15d9d commit cfbaf66

2 files changed

Lines changed: 81 additions & 0 deletions

File tree

CPP/tree/flatten_binary_tree.cpp

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#include <iostream>
2+
using namespace std;
3+
#include <stack>
4+
// Definition for a binary tree node.
5+
struct Node
6+
{
7+
int data;
8+
Node *left;
9+
Node *right;
10+
Node(int val)
11+
{
12+
data = val;
13+
left = NULL;
14+
right = NULL;
15+
}
16+
};
17+
18+
//build binary tree from user input
19+
// Input format: Enter node values in pre-order fashion. Use -1 to indicate NULL nodes
20+
Node *buildTree()
21+
{
22+
int val;
23+
cin >> val;
24+
if (val == -1)
25+
return NULL;
26+
Node *root = new Node(val);
27+
root->left = buildTree();
28+
root->right = buildTree();
29+
return root;
30+
}
31+
32+
Node *flatten(Node *root) // flatten the binary tree to a linked list in-place time: O(n) space: O(1)
33+
{
34+
if (!root)
35+
return NULL;
36+
Node *curr = root;
37+
38+
while (curr != NULL)
39+
{
40+
if (curr->left != NULL)
41+
{
42+
Node *prev = curr->left;
43+
while (prev->right)
44+
{
45+
prev = prev->right;
46+
}
47+
prev->right = curr->right;
48+
curr->right = curr->left;
49+
curr->left = NULL;
50+
}
51+
curr = curr->right;
52+
}
53+
return root;
54+
}
55+
56+
void inorder(Node *root) // inorder traversal to display the tree
57+
{
58+
if (!root)
59+
return;
60+
inorder(root->left);
61+
cout << root->data << " ";
62+
inorder(root->right);
63+
}
64+
65+
int main()
66+
{
67+
cout << "Build the binary tree (use -1 for NULL nodes): ";
68+
Node *root = buildTree(); // Example input: 1 2 4 -1 -1 5 -1 -1 3 -1 -1
69+
70+
cout << "Inorder Traversal of original tree: ";
71+
inorder(root);
72+
cout << endl;
73+
74+
root = flatten(root);
75+
76+
cout << "Inorder Traversal of flattened tree: ";
77+
inorder(root);
78+
cout << endl;
79+
80+
return 0;
81+
}

CPP/tree/flatten_binary_tree.exe

134 KB
Binary file not shown.

0 commit comments

Comments
 (0)