File tree 1 file changed +43
-0
lines changed
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ // this is the solution for problem no 623 on leetcode.
2
+ // the solution uses BFS
3
+ // https://leetcode.com/problems/add-one-row-to-tree/
4
+
5
+ class Solution {
6
+ public:
7
+ TreeNode* addOneRow (TreeNode* root, int val, int depth) {
8
+ if (root==NULL ) return root;
9
+ int ld=0 ; // to store the local depth
10
+ queue<TreeNode*> q; // a queue for performing BFS
11
+ if (depth==1 ){ // checking edge cases
12
+ TreeNode* newroot= new TreeNode (val);
13
+ newroot->left =root;
14
+ newroot->right =NULL ;
15
+ return newroot;
16
+ }
17
+ q.push (root);
18
+ while (!q.empty ()){
19
+ ++ld; // after each iteration, our local depth increases by one
20
+ int sz= q.size ();
21
+ // standard bfs template
22
+ for (int i=0 ;i<sz;i++){
23
+ TreeNode* temp= q.front ();
24
+ q.pop ();
25
+ if (ld==depth-1 ){ // checking if this is the depth after which we have to insert new nodes
26
+ TreeNode* newl= new TreeNode (val);
27
+ if (temp->left ) newl->left = temp->left ; // if current node is not the last, then assign the left subtree to new node
28
+ temp->left = newl;
29
+ TreeNode* newr= new TreeNode (val);
30
+ if (temp->right ) newr->right = temp->right ;
31
+ temp->right = newr;
32
+ }
33
+ if (temp->left )
34
+ q.push (temp->left );
35
+ if (temp->right )
36
+ q.push (temp->right );
37
+ }
38
+ if (ld==depth-1 )
39
+ return root; // to save processing time because once roots inserted, no need to change anything in tree
40
+ }
41
+ return root;
42
+ }
43
+ };
You can’t perform that action at this time.
0 commit comments