我的二叉树按顺序遍历的显示是错误的。我无法弄清楚我做错了什么。当高度为 4(包括级别 0 为 1)时,输出显示在 1-15,而不是显示为:8 4 9 2 10 5 11 1 12 6 13 3 14 7 15。
主要的:
#include <iostream>
#include "math.h"
#include "bintree.h"
using namespace std;
int main()
{
binary_tree bin;
int tmp, num, height;
cout << "Please enter a height that you wish to see: " ;
cin >> height;
cout << endl << endl;
bin.insert(num, height);
cout << "The In-Order Traversal is: " ;
bin.displayinorder();
cout << endl << endl;
system("Pause");
return 0;
}
void binary_tree::insert(int num, int height)
{
num = pow(2, height);
for(int i = 1; i < num; i++)
{
node* t = new node;
node* parent;
t-> data = i;
t-> left = NULL;
t-> right = NULL;
parent = NULL;
if(isEmpty()) root = t;
else
{
node* curr;
curr = root;
while(curr)
{
parent = curr;
if(t->data > curr->data) curr = curr->right;
else curr = curr->left;
}
if(t->data < parent->data)
parent->left = t;
else
parent->right = t;
}
}
}
void binary_tree::displayinorder()
{
inorder(root);
}
void binary_tree::inorder(node* p)
{
if(p)
{
inorder(p -> left);
cout<< " " << p->data <<" ";
inorder(p -> right);
}
}
void binary_tree::displaypreorder()
{
preorder(root);
}
void binary_tree::preorder(node* p)
{
if(p != NULL)
{
cout<<" "<< p -> data <<" ";
preorder(p -> left);
preorder(p -> right);
}
else return;
}
标题:
#ifndef BINTREE_H
#define BINTREE_H
#include <cstdlib> // Provides NULL and size_t
class binary_tree
{
private:
struct node
{
node* left;
node* right;
int data;
};
node* root;
public:
binary_tree()
{
root = NULL;
}
bool isEmpty() const
{
return root==NULL;
}
void displayinorder();
void inorder(node*);
void displaypreorder();
void preorder(node*);
void insert(int, int);
};
#endif