标签:blog http os io 2014 ar 代码 amp
很容易想到递归,实现确实不是太容易,对本人来说。
平衡二叉树是有序的,要求链表也是有序。
\
代码:
#include<iostream> //平衡二叉树转化为双向链表 using namespace std; typedef struct tree{ int data; struct tree *lchild; struct tree *rchild; }Tree,*pTree; void createBST(pTree &pHead){ int temp; scanf("%d",&temp); if(temp){ pHead = new Tree(); pHead->data = temp; createBST(pHead->lchild); createBST(pHead->rchild); }else{ pHead = NULL;a return ; } } void print(pTree p){ if(p){ print(p->lchild); cout<<p->data<<" "; print(p->rchild); }else{ return ; } } void convertList(pTree root,pTree * pLastNode){ if(root == NULL) return ; pTree cur = root; if(cur->lchild != NULL){ convertList(root->lchild,pLastNode); } cur->lchild = *pLastNode; if(*pLastNode != NULL){ (*pLastNode)->rchild = cur; } *pLastNode = cur; if(cur->rchild != NULL){ convertList(cur->rchild,pLastNode); } } void printList(const pTree cur1){ pTree cur = cur1; while(cur){ cout<<cur->data<<" "; cur = cur->rchild; } } pTree convert(pTree root){ if(NULL == root) return root; pTree pLastNode = NULL; convertList(root,& pLastNode); pTree pHead = pLastNode; while(pHead != NULL && pHead ->lchild != NULL){ pHead = pHead->lchild; } return pHead; } int main() { pTree pHead = NULL; createBST(pHead); cout<<"原平衡二叉树的中序遍历:"; print(pHead); cout<<endl; cout<<"链表的从左到右序列:"; pTree pHead1= convert(pHead); printList(pHead1); return 0; }
标签:blog http os io 2014 ar 代码 amp
原文地址:http://blog.csdn.net/buyingfei8888/article/details/38513305