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
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
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<stdio.h>
#include<stdlib.h>
# define N 20;
int count = 0;
typedef struct tree
{
int num;
struct tree* lchild;
struct tree* rchild;
}Tree;
Tree* plndex = NULL;
void add(Tree*&T, int num)
{
if (T == NULL)
{
Tree* pTree = new Tree();
pTree->num = num;
pTree->lchild = NULL;
pTree->rchild = NULL;
T = pTree;
}
else if (T->num < num)
{
add(T->rchild, num);
}
else if (T->num>num)
{
add(T->lchild, num);
}
}
void convertToList(Tree* T)
{
if (T == NULL)
{
return;
}
T->lchild = plndex;
if (plndex != NULL)
plndex->rchild = T;
plndex = T;
}
void inOrderBSTree(Tree* T)
{
if (NULL == T)
{
return;
}
else
{
inOrderBSTree(T->lchild);
convertToList(T);
inOrderBSTree(T->rchild);
}
}
int main()
{
Tree *pRoot = NULL;
add(pRoot, 10);
add(pRoot, 6);
add(pRoot, 14);
add(pRoot, 4);
add(pRoot, 8);
add(pRoot, 12);
add(pRoot, 16);
inOrderBSTree(pRoot);
return 0;
}