写出一个完整程序,实现二叉排序树的结构定义、创建和后序遍历算法,将后序遍历序列输出
时间: 2024-05-25 22:18:31 浏览: 62
二叉树的层序创建和后续遍历(代码实现)
#include <iostream>
using namespace std;
struct Node{
int data;
Node* left;
Node* right;
};
Node* create(int data){
Node* newNode = new Node;
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void insert(Node* &root, int data){
if(root == NULL){
root = create(data);
return;
}
if(data <= root->data){
insert(root->left, data);
}else{
insert(root->right, data);
}
}
void postorder(Node* root){
if(root == NULL){
return;
}
postorder(root->left);
postorder(root->right);
cout << root->data << " ";
}
int main(){
Node* root = NULL;
int arr[] = {5, 2, 8, 4, 6, 10};
int n = sizeof(arr)/sizeof(arr[0]);
for(int i=0; i<n; i++){
insert(root, arr[i]);
}
postorder(root);
return 0;
}
阅读全文