0% found this document useful (0 votes)
4 views3 pages

Tree Basic Code

This document contains a C++ implementation of a binary tree with various traversal methods, including inorder, preorder, postorder, and breadth-first search (BFS). It defines a Node class for tree nodes and a BinaryTree class for traversal functions. The main function creates a sample binary tree and demonstrates each traversal method.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Tree Basic Code

This document contains a C++ implementation of a binary tree with various traversal methods, including inorder, preorder, postorder, and breadth-first search (BFS). It defines a Node class for tree nodes and a BinaryTree class for traversal functions. The main function creates a sample binary tree and demonstrates each traversal method.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

#include <iostream>

#include <queue>
using namespace std;

// Node class
class Node {
public:
int data;
Node* left;
Node* right;

// Constructor
Node(int value) {
data = value;
left = NULL;
right = NULL;
}
};

// Binary Tree class


class BinaryTree {
public:

// DFS - Inorder Traversal


void inorder(Node* root) {
if (root == NULL)
return;

inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}

// DFS - Preorder Traversal


void preorder(Node* root) {
if (root == NULL)
return;

cout << root->data << " ";


preorder(root->left);
preorder(root->right);
}

// DFS - Postorder Traversal


void postorder(Node* root) {
if (root == NULL)
return;

postorder(root->left);
postorder(root->right);
cout << root->data << " ";
}
// BFS - Level Order Traversal
void BFS(Node* root) {

if (root == NULL)
return;

queue<Node*> q;
[Link](root);

while (![Link]()) {

Node* current = [Link]();


[Link]();

cout << current->data << " ";

if (current->left != NULL)
[Link](current->left);

if (current->right != NULL)
[Link](current->right);
}
}

// DFS using stack-like recursion


void DFS(Node* root) {

if (root == NULL)
return;

cout << root->data << " ";

DFS(root->left);
DFS(root->right);
}
};

int main() {

// Create tree
Node* root = new Node(1);

root->left = new Node(2);


root->right = new Node(3);

root->left->left = new Node(4);


root->left->right = new Node(5);

root->right->left = new Node(6);


root->right->right = new Node(7);

BinaryTree tree;
// DFS Traversals
cout << "Inorder Traversal: ";
[Link](root);

cout << "\nPreorder Traversal: ";


[Link](root);

cout << "\nPostorder Traversal: ";


[Link](root);

// BFS
cout << "\nBFS Traversal: ";
[Link](root);

// DFS
cout << "\nDFS Traversal: ";
[Link](root);

cout << endl;

return 0;
}

You might also like