程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 二叉排序樹轉化為雙向鏈表

二叉排序樹轉化為雙向鏈表

編輯:C++入門知識

#include<iostream>
using namespace std;

struct BTnode{
int value;
BTnode *left;
BTnode *right;

}*head=NULL,*tail=NULL;

BTnode *newNode(int value){//初始化一個新的節點
BTnode *Node=(BTnode *)malloc(sizeof(BTnode));
Node->left=NULL;
Node->right=NULL;
Node->value=value;
return Node;
}
BTnode *constructBT(){//構造一顆二叉排序樹
BTnode *root=newNode(10);
root->left=newNode(6);
root->right=newNode(14);
root->left->left=newNode(4);
root->left->right=newNode(8);
root->right->left=newNode(12);
root->right->right=newNode(16);
return root;
}
void Btree2DoubleList(BTnode *curr){
if(!tail){
head=tail=curr;//第一次訪問的是最小節點,一開始head,tail指針均指向它
}
else{  //從第二個節點之後,將當前節點的左指針指向鏈表尾,鏈表尾節點右指針指向當前節點,最後鏈表尾節點指向當前節點
curr->left=tail;
tail->right=curr;
tail=curr;
}
}
void transBtree2DoubleList(BTnode *curr){//中序遍歷二叉排序樹,第一次訪問的是最小節點。。。
if(curr==NULL)
return;
if(curr->left)
transBtree2DoubleList(curr->left);
Btree2DoubleList(curr);
if(curr->right)
transBtree2DoubleList(curr->right);
}
int main(){
BTnode *root=constructBT();
transBtree2DoubleList(root);
while(head)
{
cout<<head->value<<" ";
head=head->right;
}
return 0;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved