从网上找了一些面试题目,做一做
/*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 <cstdio>
#include <cstring>
using namespace std;
struct BSTreeNode
{
int m_nValue;
BSTreeNode *m_pLeft;
BSTreeNode *m_pRight;
};
BSTreeNode *CreateNode(int v) //创建新节点
{
BSTreeNode *pNew = new BSTreeNode();
pNew->m_nValue = v;
pNew->m_pLeft = pNew->m_pRight = NULL;
return pNew;
}
void BSTBuild(BSTreeNode **pRoot, int v) //创建BST
{
BSTreeNode *p = *pRoot;
if(p == NULL){
*pRoot = CreateNode(v);
}else if(v < p->m_nValue){
BSTBuild(&p->m_pLeft, v);
}else BSTBuild(&p->m_pRight, v);
}
void BSTreeIn(BSTreeNode *pRoot) //BST中序遍历,输出为有序数列
{
if(pRoot != NULL){
BSTreeIn(pRoot->m_pLeft);
printf("%d ", pRoot->m_nValue);
BSTreeIn(pRoot->m_pRight);
}
}
//BST转LIST,pRoot为当前根节点,nPre为当前节点的前驱结点,nRoot为链表的头结点
void BST2List(BSTreeNode *pRoot, BSTreeNode **nPre, BSTreeNode **nRoot)
{
if(pRoot == NULL) return ;
BST2List(pRoot->m_pLeft, nPre, nRoot);
if(*nPre == NULL){ //最左边的节点为根节点
*nRoot = pRoot;
}else{ //修改当前节点和前驱结点的指针
(*nPre)->m_pRight = pRoot;
pRoot->m_pLeft = *nPre;
}
*nPre = pRoot; //将当前节点变为前驱结点,作为右子树节点的前驱
BST2List(pRoot->m_pRight, nPre, nRoot);
}
void PrintList(BSTreeNode *pHead) //打印链表
{
while(pHead){
printf("%d ", pHead->m_nValue);
pHead = pHead->m_pRight;
}
}
int main()
{
BSTreeNode *root = NULL;
int n = 7;
int a[] = {10, 6, 4, 8, 14, 12, 16};
for(int i = 0; i < n; i++){
BSTBuild(&root, a[i]);
}
BSTreeIn(root);
printf("\n");
BSTreeNode *nRoot = NULL, *nPre = NULL;
BST2List(root, &nPre, &nRoot);
PrintList(nRoot);
printf("\n");
}