0% found this document useful (0 votes)
6 views

C++ Tree

The document contains C++ code that defines a binary tree structure using a TreeNode class. It includes a function for in-order traversal to print the values of the nodes. The main function creates a binary tree and calls the print function to display its elements.

Uploaded by

johnnystar91a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

C++ Tree

The document contains C++ code that defines a binary tree structure using a TreeNode class. It includes a function for in-order traversal to print the values of the nodes. The main function creates a binary tree and calls the print function to display its elements.

Uploaded by

johnnystar91a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include<bits/stdc++.

h>

using namespace std;

//structure to define a node in the binary tree

struct TreeNode {

int value;

struct TreeNode* left;

struct TreeNode* right;

TreeNode(int val) { //constructor to initialize the node with a value

value = val;

left = NULL;

right = NULL;

};

//function to print the binary tree elements using in-order traversal

void printBinaryTree(struct TreeNode* root) {

if (root == NULL) {

return;

// Traverse the left subtree

printBinaryTree(root->left);

// Print the value of the present node

cout << root->value << " ";

// Traverse the right subtree

printBinaryTree(root->right);

}
int main() {

struct TreeNode* root = new TreeNode(1); // Create the root of the binary tree

// Create left and right child nodes

root->left = new TreeNode(2);

root->right = new TreeNode(3);

// Create a left child for the root's left node

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

// Print the binary tree elements using in-order traversal

printBinaryTree(root);

return 0;

You might also like