注:所有题目的代码为参照v_JULY_v或者自己所写,而解答中的分析为自己所想。
1.把二元查找树转变成排序的双向链表
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
首先我们定义的二元查找树 节点的数据结构如下:
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};
解答:
在该问题中,我们通过在每次访问当前树的结点的之前记录其上一个访问的结点(因为该节点为当前访问结点在循环列表中的前驱结点),来修改二叉查找树的结构从而实现两者结构之间的转换。
在该问题的分析过程中,我再次深入理解了树的遍历的顺序问题。在前序遍历过程中,由于当前访问的结点是优先于其左右孩子结点访问的,所以在访问该结点时,是不能修改其左右子树中指针的指向的。在中序遍历过程中,由于在访问当前的结点之前,已经访问了其左子树的所有的结点,所以可以修改其左子树的结构而不影响树正确的中序遍历行为,但是依然不能修改其右子树中结点的结构。同样的,在后序遍历过程中,由于访问该结点的时候,其左右子树已经都访问过了,所以修改左右子树的结构不会影响之后的树的遍历行为。
代码:
#include <iostream>
using namespace std;
struct BSTreeNode {
int m_nValue;
BSTreeNode* m_pLeft;
BSTreeNode* m_pRight;
};
typedef BSTreeNode DoubleNode;
DoubleNode* pPre; // 用于指向当前访问结点的前驱结点
DoubleNode* pDoubleListHead;
// 注意参数的指针的引用的使用
void addBSTreeNode(BSTreeNode* &root, int value)
{
if (NULL == root) {
root = new BSTreeNode();
root->m_pLeft = NULL;
root->m_pRight = NULL;
root->m_nValue = value;
}
while (NULL != root) {
if (root->m_nValue < value) {
root = root->m_pRight;
} else if (root->m_nValue > value) {
root = root->m_pLeft;
} else {
cout << " the value has already existed! " << endl;
}
}
root = new BSTreeNode();
root->m_pLeft = NULL;
root->m_pRight = NULL;
root->m_nValue = value;
}
void addBSTreeNodeR(BSTreeNode* &root, int value)
{
cout << value << " ";
if (NULL == root) {
root = new BSTreeNode();
root->m_pLeft = NULL;
root->m_pRight = NULL;
root->m_nValue = value;
cout << endl;
} else if (root->m_nValue < value) {
cout << "R:" << root->m_nValue << " ";
addBSTreeNodeR(root->m_pRight, value);
} else if (root->m_nValue > value) {
cout << "L:" << root->m_nValue << " ";
addBSTreeNodeR(root->m_pLeft, value);
} else {
cout << "the value has already existed! " << endl;
}
}
void convertToList(BSTreeNode* pCur)
{
if (NULL != pPre) {
pPre->m_pRight = pCur;
pCur->m_pLeft = pPre;
}
else {
pDoubleListHead = pCur;
}
pPre = pCur;
cout << pCur->m_nValue << endl;
}
void traverse(BSTreeNode* &root)
{
BSTreeNode* pCur = root;
if (pCur->m_pLeft) {
traverse(pCur->m_pLeft);
}
convertToList(pCur);
if (pCur->m_pRight) {
traverse(pCur->m_pRight);
}
}
int main(void)
{
pPre = NULL;
pDoubleListHead = NULL;
BSTreeNode* root = NULL;
addBSTreeNodeR(root, 10);
addBSTreeNodeR(root, 6);
addBSTreeNodeR(root, 4);
addBSTreeNodeR(root, 8);
addBSTreeNodeR(root, 14);
addBSTreeNodeR(root, 12);
addBSTreeNodeR(root, 16);
traverse(root);
DoubleNode* pPtr = pDoubleListHead;
while (NULL != pPtr) {
cout << pPtr->m_nValue << ":";
if (pPtr->m_pLeft) {
cout << "L=";
cout << pPtr->m_pLeft->m_nValue;
cout << " ";
}
else
cout << "NULL ";
if (pPtr->m_pRight) {
cout << "R=";
cout << pPtr->m_pRight->m_nValue;
cout << " ";
}
else
cout << "NULL ";
cout << endl;
pPtr = pPtr->m_pRight;
}
return 0;
}