C++ Binary Search Tree Insertion Algorithm -


i trying finish c++ project have insert array of integers binary search tree. have use particular insertion algorithm:

insert(t, z) 1  y = nil 2  x = t.root 3  while x != nil 4      y = x 5      if z.key < x.key 6          x = x.left 7      else x = x.right 8  z.p = y 9  if y == nil 10     t.root = z 11 else if z.key < y.key 12     y.left = z 13 else y.right = z 

here code far:

main.cpp  #include <iostream> #include "binarytree.h"  using namespace std;  int main() {     binarytree tree;     int array [10] = {30, 10, 45, 38, 20, 50, 25, 33, 8, 12};      (int = 0; < 10; i++)     {         tree.add(array[i]);     }      tree.inordertreewalk();     return 0; }  void binarytree::insert(node *&t, node *&z) {      node *y = nullptr;     y = new node;     y->key = 0;     y->left = y->right = y->parent = nullptr;      node *x = t;     while (x != nullptr)     {         y = x;         if (z->key < x->key)             x = x->left;         else             x = x->right;     }     z->parent = y;     if (y == nullptr)         t = z;     else if (z->key < y->key)         y->left = z;     else         y->right = z; }  void binarytree::add(int num) {     node *newnode = nullptr;     newnode = new node;     newnode->left = newnode->right = newnode->parent = nullptr;     newnode->key=num;     insert(root, newnode); }  void binarytree::inordertreewalk(node *x) const {     if (x)     {         inordertreewalk(x->left);         cout << x->key << endl;         inordertreewalk(x->right);     } }  void binarytree::destroysubtree(node *newnode) {     if (newnode)     {         if (newnode->left)             destroysubtree(newnode->left);         if (newnode->right)             destroysubtree(newnode->right);         delete newnode;     } }   binarytree.h  #ifndef binarytree_h_ #define binarytree_h_ #include <iostream> using namespace std;  class binarytree {      private:         struct node         {             int key;             node* left;             node* right;             node* parent;         };          node *root;          void insert(node *&, node *&);         void inordertreewalk(node *) const;         void destroysubtree(node *);      public:         binarytree()             { root = nullptr; }         ~binarytree()             { destroysubtree(root); }         void add(int);         void inordertreewalk() const             { inordertreewalk(root); } };  #endif 

this program compiles, not displaying tree. know problem implementation of insertion algorithm because used different algorithm found in textbook , kept rest of code same , tree displayed in order. know t pointer root, i'm not sure if numbers being correctly stored in tree. help.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -