剑指offer之面试题27二叉搜索树与双向链表
来源:互联网 发布:怎么测试网络丢包率 编辑:程序博客网 时间:2024/05/20 15:10
问题描述:
输入一颗二叉搜索树,将该二叉搜索树转换为一个排序的双向链表。
要求不能创建任何新的结点,只能调整树中结点指针的指向。
实现代码如下:
#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#include <limits.h>struct Node{int value;struct Node *left;struct Node *right;};typedef struct Node node;void doConvertNode(node *root,node **pLastNodeInList){ if(root==NULL)return;node *currentNode = root;if(currentNode->left!=NULL){doConvertNode(currentNode->left,pLastNodeInList);}currentNode->left=*pLastNodeInList;if(*pLastNodeInList!=NULL){(*pLastNodeInList)->right=currentNode;}*pLastNodeInList=currentNode;if(currentNode!=NULL){doConvertNode(currentNode->right,pLastNodeInList);}}node *convert(node *root){if(root==NULL)return root;node *pLastNodeInList = NULL;doConvertNode(root,&pLastNodeInList);node *head = pLastNodeInList;while(head->left!=NULL){head=head->left;}return head;}int main(int argc, char *argv[]){node *root = (node *)malloc(sizeof(node));root->value=4;node *rootleft=(node *)malloc(sizeof(node));rootleft->value=2;node *rootright=(node *)malloc(sizeof(node));rootright->value=6;node *leftleft=(node *)malloc(sizeof(node));leftleft->value=1;node *leftright=(node *)malloc(sizeof(node));leftright->value=3;node *rightleft=(node *)malloc(sizeof(node));rightleft->value=5;root->left=rootleft;root->right=rootright;rootleft->left=leftleft;rootleft->right=leftright;rootright->left=rightleft;leftleft->left=NULL;leftleft->right=NULL;leftright->left=NULL;leftright->right=NULL;rightleft->left=NULL;rightleft->right=NULL;rootright->right=NULL;node *head=convert(root);while(head->right!=NULL){printf("%d\t",head->value);head=head->right;}printf("%d\n",head->value);while(head->left!=NULL){printf("%d\t",head->value);head=head->left;}printf("%d\n",head->value);return 0;}
参考资料:
剑指offer
备注:
转载请注明出处:http://blog.csdn.net/wsyw126/article/details/51383498
作者:WSYW126
0 0
- 剑指offer之面试题27:二叉搜索树与双向链表
- 剑指offer之面试题27二叉搜索树与双向链表
- 剑指Offer之面试题27:二叉搜索树与双向链表
- [剑指offer][面试题27]二叉搜索树与双向链表
- [剑指offer]面试题27 二叉搜索树与双向链表
- 剑指Offer:面试题27 二叉搜索树与双向链表
- 《剑指Offer》 面试题27:二叉搜索树与双向链表
- 《剑指Offer》学习笔记--面试题27:二叉搜索树与双向链表
- 剑指offer 面试题27—二叉搜索树与双向链表
- 剑指offer--面试题27:二叉搜索树与双向链表--Java实现
- 【剑指Offer学习】【面试题27:二叉搜索树与双向链表】
- 剑指Offer面试题27(Java版):二叉搜索树与双向链表
- 剑指Offer----面试题27:二叉搜索树与双向链表
- 剑指Offer-面试题27:二叉搜索树与双向链表
- 剑指Offer:面试题27——二叉搜索树与双向链表(java实现)
- 剑指offer面试题27:二叉搜索树与双向链表
- 剑指offer--面试题27:二叉搜索树与双向链表
- 剑指Offer面试题27(Java版):二叉搜索树与双向链表
- tableView的一些用法(持续更新)
- RGMII布线指导 RGMII Layout Guide
- Arduino 高级教程 01:基础篇
- Handler+ExecutorService(线程池)+MessageQueue模式+缓存模式
- JS正则表达式详解
- 剑指offer之面试题27二叉搜索树与双向链表
- 基于common-fileupload实现文件上传
- 读书笔记(UIKit性能优化解析和Block经典实用)(一)
- Proguard 不要混淆内部类
- PAT:树
- Codeforces Round #352 (Div. 2) ABCD
- svn的branch truck tag
- 遇到的问题总结
- 怎么用Beyond Compare对比图片差异