Search
 
SCRIPT & CODE EXAMPLE
 

CPP

cpp binary tree

A binary tree is a tree data structure in which each parent node can have at most 
two children. Each node of a binary tree consists of three items:
    data item
    address of left child
    address of right child
    
// Binary Tree in C++

#include <stdlib.h>
#include <iostream>

using namespace std;

struct node {
  int data;
  struct node *left;
  struct node *right;
};

// New node creation
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);
}

// Traverse Preorder
void traversePreOrder(struct node *temp) {
  if (temp != NULL) {
    cout << " " << temp->data;
    traversePreOrder(temp->left);
    traversePreOrder(temp->right);
  }
}

// Traverse Inorder
void traverseInOrder(struct node *temp) {
  if (temp != NULL) {
    traverseInOrder(temp->left);
    cout << " " << temp->data;
    traverseInOrder(temp->right);
  }
}

// Traverse Postorder
void traversePostOrder(struct node *temp) {
  if (temp != NULL) {
    traversePostOrder(temp->left);
    traversePostOrder(temp->right);
    cout << " " << temp->data;
  }
}

int main() {
  struct node *root = newNode(1);
  root->left = newNode(2);
  root->right = newNode(3);
  root->left->left = newNode(4);

  cout << "preorder traversal: ";
  traversePreOrder(root);
  cout << "
Inorder traversal: ";
  traverseInOrder(root);
  cout << "
Postorder traversal: ";
  traversePostOrder(root);
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: string stream in c++ 
Cpp :: c++ random number within range 
Cpp :: how to pass function as a parameter in c++ 
Cpp :: c++ max of array 
Cpp :: c++ multidimensional vector 
Cpp :: sieve cpp 
Cpp :: armstrong number in cpp 
Cpp :: push_back struct c++ 
Cpp :: initialize 2d vector 
Cpp :: char ascii c++ 
Cpp :: strlen in c++ 
Cpp :: vector size for loop 
Cpp :: how to send email in c++ program 
Cpp :: how to get the size of a vector in c++ 
Cpp :: string.begin() c++ 
Cpp :: lutris 
Cpp :: Pyramid pattren program in C++ 
Cpp :: for c++ 
Cpp :: C++ Area and Perimeter of a Rectangle 
Cpp :: c++ string to int 
Cpp :: Reverse Level Order Traversal cpp 
Cpp :: memmove 
Cpp :: Palindrome String solution in c++ 
Cpp :: fizzbuzz c++ 
Cpp :: c++ do every 1 minutes 
Cpp :: how to turn int into string c++ 
Cpp :: c++ compile to exe 
Cpp :: vector library c++ 
Cpp :: size of a matrix using vector c++ 
Cpp :: c++ random number 
ADD CONTENT
Topic
Content
Source link
Name
1+3 =