A Simple Binary Tree Implementation in C++

A very basic binary tree implementation in C++ that defines a binary tree node, adds new nodes and prints the tree. [code language="cpp"] #include <stdio.h> class Node { public: Node( int v ) { data = v; left = 0; right = 0; } int data; Node* left; Node* right; }; void Add( Node** root, Node* n ) { if ( !*root ) { *root = n; return; } if ( (*root)->data < n->data ) { Add( &(*root)->right, n ); } else { Add( &(*root)->left, n ); } } void Print( Node* node ) { if ( !node ) return; Print( node->left ); printf( "value = %i\n", node->data ); Print( node->right ); } int main() { Node* root = 0; Add( &root, new Node( 1 ) ); Add( &root, new Node( 2 ) ); Add( &root, new Node( -1 ) ); Add( &root, new Node( 12 ) ); Print( root ); return 0; } [/code] Output:

Comments

Popular posts from this blog

Using the Supervisor Controller Pattern to access View controls in MVVM

Getting started with Tesseract optical character recognition (OCR) library in Visual Studio

How to send an e-mail via Google SMTP using C#