Kamis, 31 Mei 2018

Program Menggunakan Binary Tree C++

Program Menggunakan Binary Tree C++

Script Program
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

/* A <span id="mvuhno2x61oe_1" class="mvuhno2x61oe">binary tree</span> node has data, pointer to left child
   and a pointer to right child */
struct node
{
   int data;
   struct node* left;
   struct node* right;
};

/* Prototypes for funtions needed in printPaths() */
void printPathsRecur(struct node* node, int path[], int pathLen);
void printArray(int ints[], int len);

/*Given a binary tree, print out all of its root-to-leaf
 paths, one per line. Uses a recursive helper to do the work.*/
void printPaths(struct node* node)
{
  int path[1000];
  printPathsRecur(node, path, 0);
}

/* Recursive helper function -- given a node, and an array containing
 the path from the root node up to but not including this node,
 print out all the root-leaf paths.*/
void printPathsRecur(struct node* node, int path[], int pathLen)
{
  if (node==NULL)
    return;

  /* append this node to the path array */
  path[pathLen] = node->data;
  pathLen++;

  /* it's a leaf, so print the path that led to here  */
  if (node->left==NULL && node->right==NULL)
  {
    printArray(path, pathLen);
  }
  else
  {
    /* otherwise try both subtrees */
    printPathsRecur(node->left, path, pathLen);
    printPathsRecur(node->right, path, pathLen);
  }
}


/* UTILITY FUNCTIONS */
/* Utility that prints out an array on a line. */
void printArray(int ints[], int len)
{
  int i;
  for (i=0; i<len; i++)
  {
    printf("%d ", ints[i]);
  }
  printf("\n");
}

/* utility that allocates a new node with the
   given data and NULL left and right pointers. */
struct node* newnode(int data)
{
  struct node* node = (struct node*)
                       malloc(sizeof(struct node));
  node->data = data;
  node->left = NULL;
  node->right = NULL;

  return(node);
}

/* Driver program to test above functions*/
int main()
{

 struct node *root = newnode(5);
  root->left        = newnode(4);
  root->right       = newnode(8);
  root->left->left  = newnode(11);
  root->right->left  = newnode(13);
  root->right->right  = newnode(4);
  root->left->left->left  = newnode(7);
  root->left->left->right = newnode(2);
  root->right->right->right = newnode(1);

  printPaths(root);

   double number1 = 0.0;
 double number2 = 0.0;
 double number3 = 0.0;
 double number4 = 0.0;
 double answer;
 cout <<"masukkan 4 angka dari path di atas"<<endl;
 cin>>number1;
 cin>>number2;
 cin>>number3;
 cin>>number4;

 answer = (number1 + number2 + number3 + number4) /4;
 cout<<"rata-ratanya adalah "<<answer<<endl;



  system ("pause");
  getchar();

  return 0;}

Referensi :
https://teknobloggerid.blogspot.com/2016/06/contoh-coding-binary-tree-c.html

0 komentar:

Posting Komentar