-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddOneRowToTree.cpp
More file actions
65 lines (61 loc) · 1.48 KB
/
Copy pathaddOneRowToTree.cpp
File metadata and controls
65 lines (61 loc) · 1.48 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* https://leetcode.com/problems/add-one-row-to-tree
* Tree, DFS, BFS, Binary Tree
* Medium
*/
#include <iostream>
#include <queue>
using namespace std;
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* newHead = new TreeNode;
newHead->val = val;
newHead->left = root;
return newHead;
}
queue<TreeNode*> depthQueue;
depthQueue.push(root);
int queueLen = 1;
int currDepth = 1;
while (currDepth < depth - 1) {
TreeNode* currNode = depthQueue.front();
if (currNode->left) {
depthQueue.push(currNode->left);
}
if (currNode->right) {
depthQueue.push(currNode->right);
}
queueLen--;
depthQueue.pop();
if (!queueLen) {
queueLen = depthQueue.size();
currDepth++;
}
}
while (!depthQueue.empty()) {
TreeNode* currFront = depthQueue.front();
TreeNode* newLeft = new TreeNode;
newLeft->val = val;
newLeft->left = currFront->left;
TreeNode* newRight = new TreeNode;
newRight->val = val;
newRight->right = currFront->right;
currFront->left = newLeft;
currFront->right = newRight;
depthQueue.pop();
}
return root;
}
};
int main() {
}