用队列 C++ 反转 BST 中的路径
给定一颗二叉搜索树,我们需要反转其一条特定键的路径,例如。


解决方案
对此问题的解法是,我们会建立一个队列,并将所有节点压入其中,直到到达根节点。
示例
#include <bits/stdc++.h>
using namespace std;
struct node {
int key;
struct node *left, *right;
};
struct node* newNode(int item){
struct node* temp = new node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct node* root){
if (root != NULL) {
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
void Reversing(struct node** node,
int& key, queue<int>& q1){
/* If the tree is empty then
return*/
if (node == NULL)
return;
if ((*node)->key == key){ // if we find the key
q1.push((*node)->key); // we push it into our queue
(*node)->key = q1.front(); // we change the first queue element with current
q1.pop(); // we pop the first element
}
else if (key < (*node)->key){ // if key is less than current node's value
q1.push((*node)->key); // we push the element in our queue
Reversing(&(*node)->left, key, q1); //we go to the left subtree using a recursive call
(*node)->key = q1.front(); //we reverse the elements
q1.pop(); // we pop the first element
}
else if (key > (*node)->key){ // if key greater than node key then
q1.push((*node)->key);// we push node key into queue
Reversing(&(*node)->right, key, q1);// we go to right subtree using a recursive call
(*node)->key = q1.front();// replace queue front to node key
q1.pop(); // we pop the first element
}
return;
}
struct node* insert_node(struct node* node, // function to insert node nodes in our BST
int key){
if (node == NULL)
return newNode(key); // if tree is empty we return a new node
if (key < node->key) // else we push that in our tree
node->left = insert_node(node->left, key);
else if (key > node->key)
node->right = insert_node(node->right, key);
return node; // returning the node
}
int main(){
struct node* root = NULL;
queue<int> q1;
int k = 80;
/****************Creating the BST*************************/
root = insert_node(root, 50);
insert_node(root, 30);
insert_node(root, 20);
insert_node(root, 40);
insert_node(root, 70);
insert_node(root, 60);
insert_node(root, 80);
cout << "Before Reversing :" << "\n";
inorder(root);
cout << "\n";
Reversing(&root, k, q1);
cout << "After Reversing :" << "\n";
// print inorder of reverse path tree
inorder(root);
return 0;
}输出
Before Reversing : 20 30 40 50 60 70 80 After Reversing : 20 30 40 80 60 70 50
上述代码说明
对此问题的解法是,我们只需要搜索已给的键。当我们遍历这棵树时,我们将所有节点压入一个队列,然后当我们找到值等于这个键的节点时,我们将队列前面路径中所有节点的值交换,通过这种方式,我们的路径就反转了。
总结
我们通过使用队列和递归解决了如何在二叉搜索树中反转路径的问题。我们还学习了这个 C++ 程序,以及通过它解决问题的完整流程(普通方法)。我们可以用其他语言编写同样的程序,比如 C 语言、Java 语言、Python 语言等。我们希望你喜欢这篇教程。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP