-
Notifications
You must be signed in to change notification settings - Fork 0
/
0226. Invert Binary Tree.cpp
45 lines (38 loc) · 1.23 KB
/
0226. 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
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:
//v1
// TreeNode* invertTree(TreeNode* root) {
// if (root == nullptr) return nullptr;
// TreeNode* temp = root->left;
// root->left = root->right;
// root->right = temp;
// if (root->left != nullptr) {
// invertTree(root->left);
// }
// if (root->right != nullptr) {
// invertTree(root->right);
// }
// return root;
// }
//V1
TreeNode* invertTree(TreeNode* root) {
//this version handles the case where root is nullptr
if (root == nullptr) return nullptr;
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
//we can do the recursive call on nullptrs beacuse of the first if statement
invertTree(root->left);
invertTree(root->right);
//this is only really for the first / parent recursive call
return root;
}
};