二叉树转链表

#include<cstdio>#include<cstdlib>#include<cassert>#include<list>#include<vector>#include<iterator>using namespace std;typedef struct _tree_node{ int m_nValue; struct _tree_node *m_pLeft; struct _tree_node *m_pRight;}TreeNode;TreeNode* createNode(int value){ TreeNode* pNode=(TreeNode *)malloc(sizeof(TreeNode)); assert(pNode!=NULL); pNode->m_nValue=value; pNode->m_pLeft=NULL; pNode->m_pRight=NULL; return pNode;} TreeNode* arrToTree(int *arr,int start,int end){ TreeNode *pHead=NULL; if(end>=start) { int mid=(start+end)>>1; pHead=createNode(arr[mid]); pHead->m_pLeft=arrToTree(arr,start,mid-1); pHead->m_pRight=arrToTree(arr,mid+1,end); } return pHead;}/*void printTree(TreeNode *pHead){ if(pHead==NULL) return; printTree(pHead->m_pLeft); printf(“%d “,pHead->m_nValue); printTree(pHead->m_pRight);}*//*int getTreeHeight(TreeNode *pHead){ if(pHead==NULL) return 0; return getTreeHeight(pHead->m_pLeft)>getTreeHeight(pHead->m_pRight)?getTreeHeight(pHead->m_pLeft)+1:getTreeHeight(pHead->m_pRight)+1;}*/ vector< list<TreeNode *> > find_level_list(TreeNode *pHead){ vector< list<TreeNode *> > res; int level=0; list<TreeNode *>li; li.push_back(pHead); res.push_back(li); while(!res[level].empty()) { list<TreeNode *>l; list<TreeNode *>::iterator it; for(it=res[level].begin();it!=res[level].end();it++) { TreeNode *pNode=*it; if(pNode->m_pLeft) l.push_back(pNode->m_pLeft); if(pNode->m_pRight) l.push_back(pNode->m_pRight); } ++level; res.push_back(l); } return res;}void print(vector< list<TreeNode *> > res){ vector< list<TreeNode *> >::iterator it_vec; for(it_vec=res.begin();it_vec!=res.end();it_vec++) { list<TreeNode *>li=*it_vec; list<TreeNode *>::iterator it_lis; for(it_lis=li.begin();it_lis!=li.end();it_lis++) { TreeNode *pNode=*it_lis; printf(“%d “,pNode->m_nValue); } }}int main(){ int arr[]={0,1,2,3,4,5,6,7,8,9}; int len=sizeof(arr)/sizeof(arr[0]); TreeNode *pHead=NULL; pHead=arrToTree(arr,0,len-1); vector< list<TreeNode *> >res; res=find_level_list(pHead); print(res); system(“pause”); return 0;}

,不要做刺猬能不与人结仇就不与人结仇,

二叉树转链表

相关文章:

你感兴趣的文章:

标签云: