#12580: C++簡易參考解答


shawn2000100 (東華財金)

學校 : 國立東華大學
編號 : 57300
來源 : [27.53.168.5]
最後登入時間 :
2021-09-19 19:53:19
d526. Binary Search Tree (BST) | From: [134.208.3.49] | 發表日期 : 2017-08-14 16:09

#include <iostream>
using namespace std;

struct BinTree {
int data;
BinTree *left;
BinTree *right;
BinTree ( int key = 0 ) {
data = key;
left = right = NULL;
}
};

void Insert ( int key, BinTree *root ) {
BinTree *node = new BinTree ( key );
BinTree *tmp = root;

while ( 1 ) {
if ( key >= tmp->data ) {
if ( tmp->right == NULL ) {
tmp->right = node;
break;
} else
tmp = tmp->right;
} else {
if ( tmp->left == NULL ) {
tmp->left = node;
break;
} else
tmp = tmp->left;
}
}
}

void DLR ( BinTree *root ) {
if ( root == NULL )
return;
cout << root->data << " ";
DLR ( root->left );
DLR ( root->right );
}

void Free ( BinTree *root ) {
if ( root == NULL )
return;
Free ( root->left );
Free ( root->right );
delete root;
}

int main() {
int N, M;
while ( cin >> N ) {
cin >> M;
BinTree *treeA = new BinTree ( M );
for ( int i = 1; i < N; ++i ) {
cin >> M;
Insert ( M, treeA );
}
DLR ( treeA );
cout << endl;
Free ( treeA );
}
return 0;
}

 
ZeroJudge Forum