LeetCode Question: 623. Add One Row to Tree (Level : Medium)
Note:- Scroll horizontally to see the full line of code.
/**
*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
{
int val;
int depth;
public:
void addNewNodes(TreeNode *&root, int currentDepth)
{
if (currentDepth == depth - 1)
{
if (root->left)
{
TreeNode *nextChild = root->left;
root->left = new TreeNode(val);
root->left->left = nextChild;
}
else
{
root->left = new TreeNode(val);
}
if (root->right)
{
TreeNode *nextChild = root->right;
root->right = new TreeNode(val);
root->right->right = nextChild;
}
else
{
root->right = new TreeNode(val);
}
}
currentDepth++;
if (root->left)
{
addNewNodes(root->left, currentDepth);
}
if (root->right)
{
addNewNodes(root->right, currentDepth);
}
}
TreeNode *addOneRow(TreeNode *root, int val, int depth)
{
this->val = val;
this->depth = depth;
int currentDepth = 0;
if (depth == 1)
{
TreeNode *ans = new TreeNode(val);
ans->left = root;
return ans;
}
if (root)
{
addNewNodes(root, currentDepth + 1);
}
return root;
}
};
Comments
Post a Comment