面试题总结(二)
2020-01-15 10:35
1331 查看
练习:
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 }
转载于:https://www.cnblogs.com/sxmcACM/p/4509338.html
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 【总结】50道Java线程面试题
- 常见java面试题总结
- 各大IT公司经典面试题总结
- SpringMVC系列(面试必备):SpringMVC常见面试题总结(详细回答)
- C++工程师常见的面试题总结
- 十道海量数据处理面试题与十个方法大总结
- Java基础学习总结(68)——有关Java线程方面的面试题
- Java面试题总结(二)
- 黑马程序员——面试题总结
- Android 面试题总结之Android 基础Activity(一)
- java面试题总结
- 前端面试题记录+总结
- android面试题总结加强再加强版(四)
- 对一道面试题的总结与扩展思考(关于一笔画问题的数学分析)
- php面试题:linux常用命令总结
- Android 面试题总结
- 数据库面试题总结一(范式、视图、索引、授权、事务、触发器、连接方式)
- 海量数据处理:十道面试题与十个海量数据处理方法总结
- 面试题总结5
- 【学习总结】【多线程】一些面试题