微软

来源:互联网 发布:知乎 类似岁月的电视剧 编辑:程序博客网 时间:2024/04/28 10:52

题目来源:http://bbs.csdn.net/topics/350118968  July大神的博客

第一题:

把二元查找树转变成排序的双向链表

 题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
    
  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;typedef struct BSTreeNode{int m_Value;BSTreeNode *m_pLeft;BSTreeNode *m_pRight;}BSTreeNode,*BSTree;BSTree DoubleList,head;static int i=0;void CreateBSTree(BSTree& t,int x){if(t){if(t->m_Value>x)CreateBSTree(t->m_pLeft,x);else if(t->m_Value<x)CreateBSTree(t->m_pRight,x);}else{t=new BSTreeNode;t->m_Value=x;t->m_pLeft=t->m_pRight=NULL;}}void PreOrder(BSTree t){if(t){ PreOrder(t->m_pLeft);//cout<<t->m_Value<<" ";if(i==0){head=DoubleList=t;head->m_pLeft=head->m_pRight=NULL;}else{t->m_pLeft=DoubleList;DoubleList->m_pRight=t;DoubleList=t;}i++;PreOrder(t->m_pRight);}}void ShowDoubleList(BSTree head){BSTree temp;cout<<"正向输出:";while(head){cout<<head->m_Value<<" ";temp=head;head=head->m_pRight;}cout<<endl<<"反向输出:";while(temp){cout<<temp->m_Value<<" ";temp=temp->m_pLeft;}cout<<endl;}void main(){int data[10]={10,3,4,5,2,6,7,8,1,9};BSTree t=NULL;for(int i=0;i<10;i++)CreateBSTree(t,data[i]);PreOrder(t);cout<<endl;ShowDoubleList(head);system("pause");}


0 0
原创粉丝点击