1+ /* *
2+ * Definition for a binary tree node.
3+ * struct TreeNode {
4+ * int val;
5+ * TreeNode *left;
6+ * TreeNode *right;
7+ * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+ * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+ * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+ * };
11+ */
12+ class Solution {
13+ public:
14+
15+ // getting all parent nodes for which we want to append nodes
16+ void getBfs (TreeNode* root, int depth , vector<TreeNode*>&v){
17+ if (depth==1 && root!=NULL ){
18+ v.push_back (root);
19+ return ;
20+ }
21+ if (root==NULL )return ;
22+
23+ getBfs (root->left , depth-1 , v);
24+ getBfs (root->right , depth-1 , v);
25+
26+ return ;
27+ }
28+
29+ // creating nodes
30+ TreeNode* createNode (int val){
31+ TreeNode *temp=new TreeNode;
32+ temp->val = val;
33+ return temp;
34+ }
35+
36+
37+ TreeNode* addOneRow (TreeNode* root, int val, int depth) {
38+
39+ // if depth ==1
40+ if (depth==1 ){
41+ TreeNode* temp = createNode (val);
42+ temp ->left = root;
43+ return temp;
44+ }
45+
46+
47+ vector<TreeNode*>v;
48+ getBfs (root , depth-1 , v);
49+ int s = v.size ();
50+
51+ for (int i=0 ; i<s; i++){
52+ TreeNode* temp1 = createNode (val);
53+ TreeNode* temp2 = createNode (val);
54+ TreeNode *t = v[i];
55+ if (t->left && t->right ){
56+ temp1->left =t->left ;
57+ temp2->right =t->right ;
58+ t->left = temp1;
59+ t->right = temp2;
60+ }
61+ else if (t->left && t->right ==NULL ){
62+ temp1->left =t->left ;
63+ t->left = temp1;
64+ t->right = temp2;
65+ }
66+ else if (t->left ==NULL && t->right ){
67+ temp2->right =t->right ;
68+ t->left = temp1;
69+ t->right = temp2;
70+ }
71+ else {
72+ t->left = temp1;
73+ t->right = temp2;
74+ }
75+ }
76+
77+
78+ return root;
79+
80+
81+ }
82+ };
0 commit comments