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

dsa.3 code output

The document contains a C++ program that defines a binary tree and implements a function to print its nodes level-wise. It creates a sample tree with nodes and displays the traversal output. The output shows the values of the tree nodes organized by their levels.

Uploaded by

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

dsa.3 code output

The document contains a C++ program that defines a binary tree and implements a function to print its nodes level-wise. It creates a sample tree with nodes and displays the traversal output. The output shows the values of the tree nodes organized by their levels.

Uploaded by

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

Practical No:3

Code:
#include <iostream>

#include <queue>

using namespace std;

// Definition of a Tree Node

struct TreeNode {

int val;

TreeNode* left;

TreeNode* right;

TreeNode(int x) {

val = x;

left = right = NULL;

};

// Function to print tree level-wise

void printLevelWise(TreeNode* root) {

if (root == NULL) return;

queue<TreeNode*> q;

q.push(root);

while (!q.empty()) {

int levelSize = q.size(); // Number of nodes at the current level

for (int i = 0; i < levelSize; i++) {

TreeNode* current = q.front();

q.pop();

cout << current->val << " ";

// Enqueue left and right children

if (current->left) q.push(current->left);

if (current->right) q.push(current->right);

cout << endl; // Newline after each level


}

// Driver Code

int main() {

TreeNode* root = new TreeNode(1);

root->left = new TreeNode(2);

root->right = new TreeNode(3);

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

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

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

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

cout << "Level-wise tree traversal:\n";

printLevelWise(root);

return 0;

Output:

Level-wise tree traversal:

23

4567

You might also like