-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinvertBinaryTree.cpp
74 lines (57 loc) · 1.56 KB
/
invertBinaryTree.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
#include <bits/stdc++.h>
/************************************************************
Following is the TreeNode class structure
template <typename T>
class TreeNode {
public:
T data;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T data) {
this->data = data;
left = NULL;
right = NULL;
}
};
************************************************************/
bool getPath(TreeNode<int>* root, int leaf, vector<TreeNode<int>*>& st) {
if (root == NULL)
return false;
if (root->data == leaf) {
st.push_back(root);
return true;
}
st.push_back(root);
if ((root->left && getPath(root->left, leaf, st)) || (root->right && getPath(root->right, leaf, st))) {
return true;
}
st.pop_back();
return false;
}
TreeNode<int>* invertBinaryTree(TreeNode<int>* root, TreeNode<int>* leaf) {
if (root == NULL) {
return NULL;
}
vector<TreeNode<int>*> st;
getPath(root, leaf->data, st);
TreeNode<int>* newRoot = NULL;
TreeNode<int>* parent = NULL;
if (!st.empty()) {
newRoot = parent = st.back();
st.pop_back();
}
while (!st.empty()) {
TreeNode<int>* cur = st.back();
st.pop_back();
if (cur->left == parent) {
cur->left = NULL;
parent->left = cur;
} else {
cur->right = cur->left;
cur->left = NULL;
parent->left = cur;
}
parent = parent->left;
}
return newRoot;
}