面试题总结(二)

练习:

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
};

 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <iostream>
 4 using namespace std;
 5 struct BSTreeNode
 6 {
 7     int m_nValue; // value of node
 8     BSTreeNode *m_pLeft; // left child of node
 9     BSTreeNode *m_pRight; // right child of node
10 };
11 BSTreeNode *pHead = NULL;//头节点
12 BSTreeNode *preNode = NULL; //前一个节点
13 //构造二元查找树
14 void BSTree_Create(BSTreeNode *&pRoot,int value)//在这个函数中指针要改变,注意用引用传递
15 {
16     if(pRoot == NULL)
17     {
18         BSTreeNode *p = new BSTreeNode();
19         p->m_nValue = value;
20         p->m_pRight = NULL;
21         p->m_pLeft = NULL;
22         pRoot = p;
23     }
24     else if(pRoot->m_nValue < value)
25     {
26         BSTree_Create(pRoot->m_pRight,value);
27     }
28     else if(pRoot->m_nValue > value)
29     {
30         BSTree_Create(pRoot->m_pLeft,value);
31     }
32     else
33     {
34         printf("no node\n");
35     }
36 }
37 void inOrderBST(BSTreeNode *p)
38 {
39     if(p == NULL)
40     {
41         return ;
42     }
43     //遍历左子树
44     if(p->m_pLeft != NULL)
45     {
46         inOrderBST(p->m_pLeft);
47     }
48 
49     //转换节点
50     p->m_pLeft = preNode;//左节点指向前一个节点
51     if(preNode == NULL)//左节点指向头节点
52     {
53         pHead=p;
54     }
55     else//使节点的最后一个节点右指针指向当前结点
56     {
57         preNode->m_pRight=p;
58     }
59     preNode = p;//当前节点为最后节点
60     cout<<p->m_nValue<<" ";
61 
62     //遍历右子树
63     if(p->m_pRight!= NULL)
64     {
65         inOrderBST(p->m_pRight);
66     }
67 
68 }
69 int main()
70 {
71     BSTreeNode *p1 = new BSTreeNode();
72     BSTree_Create(p1,10);
73     BSTree_Create(p1,6);
74     BSTree_Create(p1,14);
75     BSTree_Create(p1,4);
76     BSTree_Create(p1,8);
77     BSTree_Create(p1,12);
78     BSTree_Create(p1,16);
79     inOrderBST(p1);
80 }

 

posted @ 2015-05-17 11:31  天天AC  阅读(140)  评论(0编辑  收藏  举报