

寻找解决方案的方法
在这种方法中,我们将创建一个队列并推送所有节点,直到获得根节点。
p>
示例
#include 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 <key <right); }}void Reversing(struct node** node, int& key, queue& 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 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 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 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 80After Reversing :20 30 40 80 60 70 50
上述代码的解释
在这种方法中,我们只需搜索给定的键。当我们遍历树时,我们将所有节点放入队列中,现在当我们找到具有键值的节点时,我们交换排在前面的所有路径节点的值,在这个过程中,我们的路径
结论
我们使用队列和递归解决了 BST 中反转路径的问题。我们还学习了该问题的 C++ 程序以及解决该问题的完整方法(普通)。我们可以用其他语言比如C、java、python等语言来编写同样的程序。我们希望本教程对您有所帮助。
立即学习“C++免费学习笔记(深入)”;
以上就是使用队列反转二叉搜索树中的路径的C++代码的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1445214.html
微信扫一扫
支付宝扫一扫