Tree Introduction

 Declaration of tree can be divided in three parts :

  1. Create class with data, left & right pointer
  2. Node function which initialize data, left & right pointer
  3. Finally main function that assembles all
 
#include <bits/stdc++.h>
using namespace std;

// Creating node class
class Node
{
  public:
  int data;
  Node *right, *left;
};

// creating node & inserting value
Node *createNode(int new_data)
{
  Node *new_node = new Node();
  new_node->data = new_data;
  new_node->left = NULL;
  new_node->right = NULL;
  return new_node;
}

int main()
{
  // Initialize root, left & right
  Node *root=createNode(5);
  root->left=createNode(9);
  root->right=createNode(11);
  
  root->left->left=createNode(15);
  root->left->right=createNode(19);

  root->right->left=createNode(18);
  root->right->right=createNode(21);
  
  return 0;
}

No comments:

If you have any doubt or suggestion let me know in comment section.

Powered by Blogger.