Giới thiệu
Cho cây nhị phân, giá trị v và độ sâu d. Thêm một hàng các nút giá trị v ở độ sâu d. Gốc ở độ sâu 1.
Quy tắc: Với mỗi nút ở độ sâu d-1, tạo 2 nút mới giá trị v làm con trái/phải. Cây con gốc trở thành cây con của nút mới tương ứng. Nếu d=1, tạo gốc mới giá trị v, cây cũ làm con trái.
Thuật toán: DFS/BFS đến độ sâu d-1
Sử dụng stack hoặc queue để duyệt cây, theo dõi độ sâu. Khi đến độ sâu d-1, chèn 2 nút mới.
Cài đặt C++ (Dùng stack)
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
TreeNode* addOneRow(TreeNode* root, int v, int d) {
if (d == 1) {
TreeNode* newRoot = new TreeNode(v);
newRoot->left = root;
return newRoot;
}
stack<pair<TreeNode*, int>> st;
st.push({root, 1}); // (node, depth)
while (!st.empty()) {
auto [node, depth] = st.top(); st.pop();
if (depth == d - 1) {
TreeNode* newLeft = new TreeNode(v);
TreeNode* newRight = new TreeNode(v);
newLeft->left = node->left;
newRight->right = node->right;
node->left = newLeft;
node->right = newRight;
} else {
if (node->left) st.push({node->left, depth + 1});
if (node->right) st.push({node->right, depth + 1});
}
}
return root;
}
};
Ví dụ
Cây: [4,2,6,3,1,5], v=1, d=2
Kết quả: [4,1,1,2,6,3,1,5] (theo level order).
Độ phức tạp
- Thời gian: O(N) – duyệt tất cả nút đến độ sâu d-1.
- Không gian: O(N) – stack trong trường hợp xấu (cây lệch).
LeetCode 623 "Add One Row to Tree".