-
Notifications
You must be signed in to change notification settings - Fork 0
/
45_invert-binary-tree.cpp
105 lines (89 loc) · 2.33 KB
/
45_invert-binary-tree.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
// DATE: 07-Aug-2023
/* PROGRAM: 45_Tree - Invert Binary Tree
https://leetcode.com/problems/invert-binary-tree/
Given the root of a binary tree, invert the tree, and return its root.
Example 1:
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Example 2:
Input: root = [2,1,3]
Output: [2,3,1]
Example 3:
Input: root = []
Output: []
*/
// @ankitsamaddar @Aug_2023
#include <iostream>
#include <queue>
#include <vector>
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) {}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == NULL) return NULL;
TreeNode* left = root->left;
TreeNode* right = root->right;
root->left = invertTree(right);
root->right = invertTree(left);
return root;
}
};
TreeNode* createTree(vector<int>& nums) {
if (nums.empty()) {
return NULL;
}
TreeNode* root = new TreeNode(nums[0]);
queue<TreeNode*> q;
q.push(root);
int i = 1;
while (!q.empty() && i < nums.size()) {
TreeNode* node = q.front();
q.pop();
if (nums[i] != INT_MIN) {
node->left = new TreeNode(nums[i]);
q.push(node->left);
}
i++;
if (i < nums.size() && nums[i] != INT_MIN) {
node->right = new TreeNode(nums[i]);
q.push(node->right);
}
i++;
}
return root;
}
string formatOutput(TreeNode* root) {
string result = "[";
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node != NULL) {
result += to_string(node->val);
result += ",";
q.push(node->left);
q.push(node->right);
}
}
result.pop_back();
result += "]";
return result;
}
int main() {
vector<int> nums = {4, 2, 7, 1, 3, 6, 9};
TreeNode* root = createTree(nums);
Solution sol;
TreeNode* invertedRoot = sol.invertTree(root);
string output = formatOutput(invertedRoot);
cout << output << endl; // expected output: [4,7,2,9,6,3,1]
return 0;
}