-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInvert binary tree.cpp
More file actions
47 lines (40 loc) · 1.33 KB
/
Invert binary tree.cpp
File metadata and controls
47 lines (40 loc) · 1.33 KB
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
/*
Platform :- Leetcode
Approach :- Store the pointer to root in some variable now perform bfs on the tree and swap left and right children and now return the varible that stored the pointer to root
take care of null root pointer.
*/
/**
* Definition for a binary tree node.
* 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)return root;
TreeNode*node = root;
queue<TreeNode*>bfs;
bfs.push(root);
while(!bfs.empty()){
int c = bfs.size();
for(int i=0;i<bfs.size();++i){
TreeNode* temp = bfs.front();
bfs.pop();
TreeNode*z=temp->left;
temp->left = temp->right;
temp->right=z;
if(temp->left){
bfs.push(temp->left);
}
if(temp->right)bfs.push(temp->right);
}
}
return node;
}
};