写一个c++程序,将顺序二叉树转化为二叉链表
时间: 2024-01-17 10:19:06 浏览: 96
好的,以下是将顺序二叉树转化为二叉链表的C++程序,希望能够帮到你:
```c++
#include<iostream>
#include<queue>
using namespace std;
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};
// 将顺序二叉树转化为二叉链表
void convertSeqTreeToLinkedList(TreeNode* root) {
if (root == NULL) {
return;
}
queue<TreeNode*> q;
q.push(root);
TreeNode* preNode = NULL;
while (!q.empty()) {
TreeNode* curNode = q.front();
q.pop();
if (preNode != NULL) {
preNode->right = curNode;
}
preNode = curNode;
if (curNode->left != NULL) {
q.push(curNode->left);
}
if (curNode->right != NULL) {
q.push(curNode->right);
}
curNode->left = NULL;
}
}
// 打印二叉链表
void printLinkedList(TreeNode* root) {
while (root != NULL) {
cout << root->val << " ";
root = root->right;
}
cout << endl;
}
int main() {
TreeNode* root = new TreeNode('A');
root->left = new TreeNode('B');
root->right = new TreeNode('C');
root->left->left = new TreeNode('D');
root->left->right = new TreeNode('E');
root->right->left = new TreeNode('F');
root->right->right = new TreeNode('G');
convertSeqTreeToLinkedList(root);
printLinkedList(root);
return 0;
}
```
该程序采用了广度优先搜索的思想,使用队列来实现二叉树的层次遍历。在遍历过程中,不断将当前节点的右指针指向队列中下一个节点,实现二叉链表的构建。最后,调用 `printLinkedList` 函数来打印转化后的二叉链表。
阅读全文