簡體   English   中英

二叉樹有序遍歷顯示錯誤

[英]Binary Tree inorder traversal display wrong

我的二叉樹有序遍歷的顯示錯誤。 我不知道我在做什么錯。 當高度為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

我認為您不清楚順序的含義。 1 .. 15是按順序遍歷包含值1 .. 15的二叉搜索樹的預期輸出。您給出的序列聽起來像是平衡二叉搜索樹上的預排序

換句話說,遍歷代碼對於順序遍歷是正確的。

就是說,您的樹生成代碼不會生成平衡的樹。 順序遍歷不會暴露出這種情況,但是順序遍歷或后序遍歷會暴露出來。 因為您按遞增順序插入所有值,所以您將得到一棵完全由正確的子代組成的樹。 在遍歷中添加一些cout語句,以了解我的意思。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM