我想获得以下输出
Preorder : 50 5 20 15 27 42 35 25 55 70 60 80 95 90 75
Inorder : 5 15 20 25 27 35 42 50 55 60 70 75 80 90 95
Postorder: 5 20 15 27 42 35 25 55 70 60 80 95 90 75 50
相反,我得到了这个
Preorder : 136161285312597531284813109128551336214133138721362114128146401438414645
Inorder : 531259712848128531285513109133621361613621138721412814133143841464014645
Postorder: 531284812597128551336213109128531362114128138721438414645146401413313616
这是我的代码
#include "stdafx.h"
#include<iostream>
using namespace std;
struct Node {
int data;
Node *left;
Node *right;
};
//Preorder Funcation
void Preorder(struct Node *root) {
if (root == NULL) return; // if tree/sub-tree is empty, return and exit
cout << root->data; // Visit
Preorder(root->left); // Move left
Preorder(root->right); // move right
}
//Inorder Funcation
void Inorder(Node *root) {
if (root == NULL) return; // if tree/sub-tree is empty, return and exit
Inorder(root->left); //Move left
cout << root->data; //Visit
Inorder(root->right); // move right
}
//Postorder Funcation
void Postorder(Node *root) {
if (root == NULL) return; // if tree/sub-tree is empty, return and exit
Postorder(root->left); // Move left
Postorder(root->right); // move right
cout << root->data; // Visit
}
// Function to Insert Node in a Binary Search Tree
Node* Insert(Node *root, int data) {
if (root == NULL) {
root = new Node();
root->data = data;
root->left = root->right = NULL;
}
else if (data <= root->data)
root->left = Insert(root->left, data);
else
root->right = Insert(root->right, data);
return root;
}
int main() {
Node *root = NULL;
root = Insert(root, '50');
root = Insert(root, '75');
root = Insert(root, '25');
root = Insert(root, '15');
root = Insert(root, '60');
root = Insert(root, '35');
root = Insert(root, '90');
root = Insert(root, '42');
root = Insert(root, '20');
root = Insert(root, '27');
root = Insert(root, '5');
root = Insert(root, '55');
root = Insert(root, '95');
root = Insert(root, '80');
root = Insert(root, '70');
cout << "Preorder: "; //Diaplay Nodes in Preorder.
Preorder(root);
cout << "\n";
cout << "Inorder: "; //Display Nodes in Inorder
Inorder(root);
cout << "\n";
cout << "Postorder: "; //Display Nodes in Postorder
Postorder(root);
cout << "\n";
return 0;
}