forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse tree path.cpp
122 lines (102 loc) · 2.52 KB
/
Reverse tree path.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// CPP program to Reverse Tree path
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node {
int data;
struct Node *left, *right;
};
// 'data' is input. We need to reverse path from
// root to data.
// 'level' is current level.
// 'temp' that stores path nodes.
// 'nextpos' used to pick next item for reversing.
Node* reverseTreePathUtil(Node* root, int data,
map<int, int>& temp, int level, int& nextpos)
{
// return NULL if root NULL
if (root == NULL)
return NULL;
// Final condition
// if the node is found then
if (data == root->data) {
// store the value in it's level
temp[level] = root->data;
// change the root value with the current
// next element of the map
root->data = temp[nextpos];
// increment in k for the next element
nextpos++;
return root;
}
// store the data in perticular level
temp[level] = root->data;
// We go to right only when left does not
// contain given data. This way we make sure
// that correct path node is stored in temp[]
Node *left, *right;
left = reverseTreePathUtil(root->left, data, temp,
level + 1, nextpos);
if (left == NULL)
right = reverseTreePathUtil(root->right, data,
temp, level + 1, nextpos);
// If current node is part of the path,
// then do reversing.
if (left || right) {
root->data = temp[nextpos];
nextpos++;
return (left ? left : right);
}
// return NULL if not element found
return NULL;
}
// Reverse Tree path
void reverseTreePath(Node* root, int data)
{
// store per level data
map<int, int> temp;
// it is for replacing the data
int nextpos = 0;
// reverse tree path
reverseTreePathUtil(root, data, temp, 0, nextpos);
}
// INORDER
void inorder(Node* root)
{
if (root != NULL) {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in above diagram
Node* root = newNode(7);
root->left = newNode(6);
root->right = newNode(5);
root->left->left = newNode(4);
root->left->right = newNode(3);
root->right->left = newNode(2);
root->right->right = newNode(1);
/* 7
/ \
6 5
/ \ / \
4 3 2 1 */
int data = 4;
// Reverse Tree Path
reverseTreePath(root, data);
// Traverse inorder
inorder(root);
return 0;
}