这是一颗二叉搜索树,可以按层次遍历和按先序、中序、后序遍历。
源码
#include<iostream>
using namespace std;
#include<queue>
struct Node
{
int data;
Node* left;
Node* right;
};
Node* getnewNode(int n)
{
Node* temp;
temp = new Node;
temp->data = n;
temp->left = NULL;
temp->right = NULL;
return temp;
}
void Insert(Node*& root, int n)
{
if (root == NULL)
root = getnewNode(n);
else if (n <= root->data)
Insert(root->left, n);
else if (n > root->data)
Insert(root->right, n);
}
//层级遍历
void Levelorder(Node* root)
{
if (root == NULL)
return;
queue<Node*>Q;
Q.push(root);
while (!Q.empty())
{
Node* current;
current = Q.front();
cout << current->data << " ";
Q.pop();
if (current->left != NULL) Q.push(current->left);
if (current->right != NULL) Q.push(current->right);
}
}
//前序遍历
void Preorder(Node* root)
{
if (root == NULL) return;
cout << root->data << " ";
Preorder(root->left);
Preorder(root->right);
}
//中序遍历
void Inorder(Node* root)
{
if (root == NULL) return;
Inorder(root->left);
cout << root->data << " ";
Inorder(root->right);
}
//后序遍历
void Postorder(Node* root)
{
if (root == NULL) return;
Postorder(root->left);
Postorder(root->right);
cout << root->data << " ";
}
int main()
{
Node* root = NULL;
Insert(root, 5);
Insert(root, 4);
Insert(root, 7);
Insert(root, 6);
Insert(root, 8);
Insert(root, 1);
Insert(root, 2);
cout << "层次遍历:";
Levelorder(root);
cout << endl << "前序遍历:";
Preorder(root);
cout << endl << "中序遍历:";
Inorder(root);
cout << endl << "后序遍历:";
Postorder(root);
}