Skip to content

Create 623. Add One Row to Tree #458

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions 623. Add One Row to Tree
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* 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* addOneRow(TreeNode* root, int val, int depth) {
if (depth == 1) {
TreeNode* newRoot = new TreeNode(val);
newRoot->left = root;
return newRoot;
}

TreeNode *result = addRow(root, val, depth);
return result;
}

TreeNode* addRow(TreeNode *currentNode, int val, int depth) {
if (currentNode == nullptr)
return currentNode;

if (depth == 2) {
TreeNode *newLeftNode = new TreeNode(val);
TreeNode *newRightNode = new TreeNode(val);
newLeftNode->left = currentNode->left;
newRightNode->right = currentNode->right;
currentNode->left = newLeftNode;
currentNode->right = newRightNode;
return currentNode;
}

currentNode->left = addRow(currentNode->left, val, depth - 1);
currentNode->right = addRow(currentNode->right, val, depth - 1);
return currentNode;
}
};
Loading