Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

CT-[Roll No.]CT-79 Data Structures Algorithms and ApplicationsLab Session: [No.

8]

[LAB #09]

Binary Trees
TASK 1:Write a method for finding the sum of all elements in a binary
tree.

SOLUTION:

OUTPUT
TASK 2:Write a method for checking the existence of path with given sum. That means, given a sum,

check whether there exist a path from root to any of the nodes.

SOLUTION:

1
CT-[Roll No.]CT-79 Data Structures Algorithms and ApplicationsLab Session: [No.8]

OUTPUT

1
CT-[Roll No.]CT-79 Data Structures Algorithms and ApplicationsLab Session: [No.8]

TASK 3: Write a method for finding the number of half nodes (nodes with only one child) in the
binary tree.
SOLUTION:

OUTPUT

Task 1 lab 9
#include <iostream>
using namespace std;
struct Node {

1
CT-[Roll No.]CT-79 Data Structures Algorithms and ApplicationsLab Session: [No.8]

int val;
Node* left;
Node* right;
};

void preorder_traversal(Node* root) {


if (root == nullptr) return;

// Visit the root node


cout << root->val << " ";

// Recursively traverse the left subtree


preorder_traversal(root->left);

// Recursively traverse the right subtree


preorder_traversal(root->right);
}

int main() {

Node* root = new Node{1, nullptr, nullptr};


root->left = new Node{2, nullptr, nullptr};
root->right = new Node{3, nullptr, nullptr};
root->left->left = new Node{4, nullptr, nullptr};
root->left->right = new Node{5, nullptr, nullptr};
root->right->left = new Node{6, nullptr, nullptr};
root->right->right = new Node{7, nullptr, nullptr};

cout << "Pre-order traversal: ";


preorder_traversal(root);
cout << endl;

return 0;
}

Output:

1
CT-[Roll No.]CT-79 Data Structures Algorithms and ApplicationsLab Session: [No.8]

TASK 2: Implement post-order traversal using the above code.

#include <iostream>
using namespace std;
struct Node {
int val;
Node* left;
Node* right;
};

void postorder_traversal(Node* root) {


if (root == nullptr) return;

// Recursively traverse the left subtree


postorder_traversal(root->left);

// Recursively traverse the right subtree


postorder_traversal(root->right);
// Visit the root node
cout << root->val << " ";
}

int main() {

Node* root = new Node{1, nullptr, nullptr};


root->left = new Node{2, nullptr, nullptr};
root->right = new Node{3, nullptr, nullptr};
root->left->left = new Node{4, nullptr, nullptr};
root->left->right = new Node{5, nullptr, nullptr};
root->right->left = new Node{6, nullptr, nullptr};
root->right->right = new Node{7, nullptr, nullptr};

cout << "Post-order traversal: ";

1
CT-[Roll No.]CT-79 Data Structures Algorithms and ApplicationsLab Session: [No.8]

postorder_traversal(root);
cout << endl;

return 0;
}

1
CT-[Roll No.]CT-79 Data Structures Algorithms and ApplicationsLab Session: [No.8]

1
CT-[Roll No.]CT-79 Data Structures Algorithms and ApplicationsLab Session: [No.8]

You might also like