Program Binary Tree Dengan C++

#include <bits/stdc++.h> //simpulan dari beberapa library

using namespace std;

class BinaryTreeNode {
friend void visit(BinaryTreeNode *);
friend void inorder(BinaryTreeNode *);
friend void preorder(BinaryTreeNode *);
friend void postorder(BinaryTreeNode *);
friend void levelorder(BinaryTreeNode *);

public:
  BinaryTreeNode(){
  LeftChild = RightChild = NULL;
  }
  BinaryTreeNode(int e){
  data = e;
  LeftChild = RightChild = NULL;
  }
  BinaryTreeNode(int e, BinaryTreeNode *l, BinaryTreeNode *r){
  data = e;
  LeftChild = l;
  RightChild = r;
  }


  private:
  int data;
  BinaryTreeNode *LeftChild, *RightChild;
};



void visit(BinaryTreeNode *x){ //print
cout<< x->data << ' ';
}

void preorder(BinaryTreeNode *t){
if(t){
visit(t);
preorder(t->LeftChild);
preorder(t->RightChild);
}
}

void inorder(BinaryTreeNode *t){
if(t){
preorder(t->LeftChild);
visit(t);
preorder(t->RightChild);
}
}

void postorder(BinaryTreeNode *t){
if(t){
preorder(t->LeftChild);
preorder(t->RightChild);
visit(t);
}
}

void levelorder(BinaryTreeNode * t){
    if (t == NULL) return;

 
    queue<BinaryTreeNode *> q;
   
 
    BinaryTreeNode *curr;


    q.push(t);
    q.push(NULL);

    while (q.size() > 1)
    {
        curr = q.front();
        q.pop();
       
     
        if (curr == NULL)
        {
           q.push(NULL);
          // cout << "\n";
        }
       
        else {
           
         
            if(curr->LeftChild)
            q.push(curr->LeftChild);
           
           
            if(curr->RightChild)
            q.push(curr->RightChild);
           
            cout << curr->data << " ";
        }
    }
}

/*
void levelorder(BinaryTreeNode *t){
LinkedQueue<BinaryTreeNode* > Q;
while (t) {
Visit(t);
if (t->LeftChild) Q.Add(t->LeftChild)
if (t->RightChild) Q.Add(t->RightChild);
try {Q.Delete(t);}
catch (OutOfBounds) {return;}
}
}
*/

/*void levelorder(BinaryTreeNode *t){
if(t){
visit(t);
preorder(t->LeftChild);
preorder(t->RightChild);

}
}*/


int main(){
BinaryTreeNode *P = new BinaryTreeNode(2);
BinaryTreeNode *Q = new BinaryTreeNode(3);
BinaryTreeNode *R = new BinaryTreeNode(1, P,Q);
cout<<"preorder: \n";
preorder(R);
cout<<endl;
cout<<"inorder: \n";
inorder(R);
cout<<endl;
cout<<"postorder: \n";
postorder(R);
cout<<endl;
cout<<"levelorder : \n";
levelorder(R);
cout<<endl<<endl;
cout<<"terus mencoba meski kau terus jatuh\n";
cout<<"semua akan indah pada waktunya :) \n";
cout<<"author by dewieza";

return 0;
}




Posting Komentar

Lebih baru Lebih lama