1 BFS
适用场景:有固定初始树节点的路径搜索问题,当已知固定终点时可用双向BFS进行优化
void bfs(TreeNode* start, TreeNode* target) {
// 1.初始化队列+记录
queue<TreeNode*> q;
set<TreeNode*> visited; // 避免走回头路
q.push(start);
visited.add(start);
int step = 0; // 记录步数
while (!q.empty()) {
int sz = q.size();
// 2.从队列中取数据
for (int i=0;i<sz;i++) {
TreeNode* e_ptr = q.front(); q.pop();
// 3.判断是否达到终点
if (e_ptr == target) { // e_ptr->left == nullptr 等
return step; // 按题目要求返回所需东西
}
// 4.没到终点则继续遍历
//--4.1 二叉树
if (e_ptr->left != nullptr) {
q.push(e_ptr->left);
vistied.add(e_ptr->left);
}
if (e_ptr->right != nullptr) {
q.push(e_ptr->right);
vistied.add(e_ptr->right);
}
//--4.2 N叉树
for (TreeNode node : e_ptr) {
if (node not in visited) {
q.push(node);
visited.add(node);
}
}
}
step++;
}
}
2 BST二叉搜索树
2.1 BST的构造
输入:严格升序的数组nums
class Solution {
public:
void recursive(vector<int>& nums, TreeNode* root, int left, int right) {
if (left > right) return;
int mid = (left + right) / 2;
root->val = nums[mid];
if (left < mid)
root->left = new TreeNode(nums[(left + mid) / 2]);
if (mid < right)
root->right = new TreeNode(nums[(mid + right) / 2]);
recursive(nums, root->left, left, mid - 1);
recursive(nums, root->right, mid + 1, right);
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
if (nums.empty()) return nullptr;
TreeNode* root = new TreeNode(0);
recursive(nums, root, 0, nums.size() - 1);
return root;
}
};
2.2 BST的遍历
class Solution {
public:
TreeNode* BST(TreeNode* root, int key) {
if (!root) return nullptr;
if (key < root->val)
root->left = BST(root->left, key);
if (key > root->val)
root->right = BST(root->right, key);
if (key == root->val) {
// 找到目标,做点什么
}
return root;
}
};
持续积累中~
附录:本专题刷题列表
致谢
感谢「代码随想录」公众号梳理的思路,欢迎大家关注这位大佬的公号