0%

LeetCode 623. Add One Row to Tree

题目

原题在此

解析

常规的level order traversal即可, 没什么难度.

代码

c++

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
/**
* 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 v, int d) {
if(!root) return root;
// if(d == 1) return make_shared<TreeNode>(v, root, NULL);
if(d == 1) {
TreeNode * foo = new TreeNode(v, root, NULL);
return foo;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty() && d) {
if(!--d) return root;
int n = q.size();
for(int i = 0; i < n; ++i) {
TreeNode* tmp = q.front();
q.pop();
if(d == 1) {
TreeNode* l = tmp->left;
TreeNode* r = tmp->right;
tmp->left = new TreeNode(v);
tmp->right = new TreeNode(v);
tmp->left->left = l;
tmp->right->right = r;
} else {
if(tmp -> left) q.push(tmp -> left);
if(tmp -> right) q.push(tmp -> right);
}
}
}
return root;
}
};