源自:http://blog.csdn.net/lilypp/article/details/6525256
将搜索二叉树转换成链表,不能创建新的节点,只能改变指针的指向。
无论是转换成单向链表还是双向链表,节点的顺序都是:1-2-3-4-5-6-7,等于中序遍历的顺序。
【1.1 二叉树-->双向链表】
二叉树是一种很适合使用递归算法的数据结构,考虑根结点和其左右子树,如果左右子树都已经完成转换了,那么只需要将左子树的最大结点和根连接,将根和右子树的最小结点连接即完成整棵数的转换。
- //搜索二叉树->双链表
- void BinaryTreeToDoublyList(BiTree &root)
- {
- if (root == NULL)
- return;
- if (root->lChild == NULL && root->rChild == NULL)
- return;
- BiNode* left = root->lChild;
- BiNode* right = root->rChild;
- BinaryTreeToDoublyList(left);
- BinaryTreeToDoublyList(right);
- //找到左子树的最大结点
- if(left)
- {
- while(left->rChild)
- {
- left = left->rChild;
- }
- left->rChild = root;
- root->lChild = left;
- }
- if (right)
- {
- //找到右子树的最大结点
- while(right->lChild)
- {
- right = right->lChild;
- }
- right->lChild = root;
- root->rChild = right;
- }
- }
- void BinaryTreeToDoublyListMain(BiTree &root)
- {
- if (root == NULL)
- return;
- BinaryTreeToDoublyList(root);
- //root指向双向链表头
- if (root->lChild)
- root = root->lChild;
- }
【1.2 二叉树-->双向链表】
递归处理左右子树,再将左子树连上根,再连上右子树,得到链表。函数返回头节点方便链接操作。
- void BinaryTreeToDoublyList_2(BiNode* root, BiNode** head)
- {
- if (root == NULL)
- {
- *head = NULL;
- return;
- }
- BiNode* leftHead = NULL;
- BiNode* rightHead = NULL;
- //转换左右子树
- BinaryTreeToDoublyList_2(root->lChild, &leftHead);
- BinaryTreeToDoublyList_2(root->rChild, &rightHead);
- if (leftHead == NULL)
- *head = root;
- else
- *head = leftHead;
- //将左右子链表链接起来
- if (leftHead != NULL)
- {
- //找到左子链表的末尾结点
- BiNode* leftTail = leftHead;
- while(leftTail->rChild)
- leftTail = leftTail->rChild;
- //左子链表连上根
- leftTail->rChild = root;
- if (root != NULL)
- root->lChild = leftTail;
- }
- if (root != NULL)
- {
- //根连上右子链表
- root->rChild = rightHead;
- if (rightHead != NULL)
- rightHead->lChild = root;
- }
- }
【2. 二叉树-->单向链表】
与1.2类似,递归处理左右子树,但是要记住子链表的首尾结点,方便连接操作。对于单链表来说,从head开始,沿着rChild,可以遍历所有结点,而结点的lChild值和之前二叉树时的值一样。
- //搜索二叉树->单链表
- void BinaryTreeToSinglyList(BiNode* root, BiNode** head, BiNode** tail)
- {
- if (root == NULL)
- {
- *head = NULL;
- *tail = NULL;
- return;
- }
- BiNode* leftHead = NULL;
- BiNode* leftTail = NULL;
- BiNode* rightHead = NULL;
- BiNode* rightTail = NULL;
- BinaryTreeToSinglyList(root->lChild, &leftHead, &leftTail);
- BinaryTreeToSinglyList(root->rChild, &rightHead, &rightTail);
- if (leftHead == NULL)
- *head = root;
- else
- *head = leftHead;
- if (rightTail == NULL)
- *tail = root;
- else
- *tail = rightTail;
- //将左右子链表链接起来
- if (leftTail != NULL)
- leftTail->rChild = root;
- if (root != NULL)
- root->rChild = rightHead;
- }