我的二叉树按顺序遍历的显示是错误的。我无法弄清楚我做错了什么。当高度为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
答案 0 :(得分:4)
我认为您不清楚按顺序的含义。 1 .. 15是包含值1 ...的二进制搜索树的有序遍历的预期输出。您给出的序列听起来像预订在平衡二叉搜索树。
换句话说,您的遍历代码对于有序遍历是正确的。
也就是说,您的树生成代码不会生成平衡树。有序遍历不会暴露,但是预订或后序遍历。因为您按递增顺序插入所有值,所以您将得到一个完全由正确子项构成的树。在遍历中添加一些cout
语句,看看我的意思。