Professional Documents
Culture Documents
Week 9 Lab A
Week 9 Lab A
Week 9 Lab A
ENROLLEMENT NO –LATG10090
1.Write a program to construct a k-ary tree of any order greater than 2 having at least 10 nodes. Now
traverse the tree using BFS & DFS.
DFS:
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node *children[4];
Node(int val)
{
data = val;
}
};
void inorder(Node *node) {
if (node == NULL)
return;
for (int i = 0; i < 3; i++)
inorder(node->children[i]);
cout<< node->data << " ";
inorder(node->children[3]);
}
void preorder(Node *node)
{
if (node == NULL)
return;
cout<< node->data << " ";
for (int i = 0; i < 3; i++)
preorder(node->children[i]);
preorder(node->children[3]);
}
void postorder(Node *node)
{
if (node == NULL)
return;
for (int i = 0; i < 3; i++)
postorder(node->children[i]);
postorder(node->children[3]);
cout<< node->data << " ";
}
int main() {
Node* root = new Node(1);
root->children[0] = new Node(2);
root->children[1] = new Node(3);
root->children[2] = new Node(4);
root->children[0]->children[0] = new Node(5);
root->children[0]->children[1] = new Node(6);
root->children[0]->children[2] = new Node(7);
root->children[0]->children[0]->children[0] = new Node(8);
root->children[0]->children[0]->children[1] = new Node(9);
root->children[0]->children[0]->children[2] = new Node(10);
inorder(root);
cout<<endl;
postorder(root);
cout<<endl;
preorder(root);
return 0;
}
BFS:
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int key;
vector<Node *>child;
};
Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
return temp;
}
void LevelOrderTraversal(Node * root)
{
if (root==NULL)
return;
queue<Node *> q;
q.push(root);
while (!q.empty())
{
int n = q.size();
while (n > 0)
{
Node * p = q.front();
q.pop();
cout << p->key << " ";
return 0;
}
3.You are given a k-ary tree of order greater than 2 having at least 10 nodes. Each node has an
integer key. Device a way to check whether the sum of the keys of all the nodes is even or not.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node* left, *right;
};
4.You are given a k-ary tree of order greater than 2 having at least 10 nodes. Each node has an
integer key. Device a way to print the count of nodes having odd keys and even keys.
#include<bits/stdc++.h>
class Node
public :
int data;
int length;
Node()
length = 0;
data = 0;
length = n;
data = data_;
};
if (node == NULL)
return;
calcOddEvenNode(node->children[i]);
if(node->data%2==0)
evensum++;
else
oddsum++;
calcOddEvenNode(node->children[total - 1]);
rec_ctr++;
int main()
int n = 3;
calcOddEvenNode(root);
return 0;