[英]Binary Tree inorder traversal display wrong
The display for my binary tree in-order traversal is wrong. 我的二叉树有序遍历的显示错误。 I cant figure out what I'm doing wrong.
我不知道我在做什么错。 The output is showing up at 1-15 when the height is 4 (including level 0 as 1) instead of showing up as : 8 4 9 2 10 5 11 1 12 6 13 3 14 7 15.
当高度为4(包括级别0为1)时,输出显示为1-15,而不是显示为:8 4 9 2 10 5 11 1 12 6 13 3 14 7 15。
main: 主要:
#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;
}
header: 标题:
#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
I think you are unclear what in-order means. 我认为您不清楚顺序的含义。 1 .. 15 is the expected output for in-order traversal of a binary search tree containing the values 1 .. 15. The sequence you gave sounds like pre-order on a balanced binary search tree.
1 .. 15是按顺序遍历包含值1 .. 15的二叉搜索树的预期输出。您给出的序列听起来像是平衡二叉搜索树上的预排序 。
In other words, your traversal code is correct for in-order traversal. 换句话说,遍历代码对于顺序遍历是正确的。
That said, your tree generation code does not produce a balanced tree. 就是说,您的树生成代码不会生成平衡的树。 An in-order traversal won't expose that, but a pre-order or post-order traversal will.
顺序遍历不会暴露出这种情况,但是顺序遍历或后序遍历会暴露出来。 Because you insert all of the values in increasing sequential order, you will get a tree made entirely of right children.
因为您按递增顺序插入所有值,所以您将得到一棵完全由正确的子代组成的树。 Add some
cout
statements to your traversal to see what I mean. 在遍历中添加一些
cout
语句,以了解我的意思。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.