#include <iostream>
using namespace std;
struct BinaryTreeNode {
BinaryTreeNode* left;
BinaryTreeNode* right;
int val;
BinaryTreeNode(int value) {
left = NULL;
right = NULL;
val = value;
}
};
void inorder(BinaryTreeNode* root) {
if (root == NULL)
return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
void preorder(BinaryTreeNode* root) {
if (root == NULL)
return;
cout << root->val << " ";
preorder(root->left);
preorder(root->right);
}
void postorder(BinaryTreeNode* root) {
if (root == NULL)
return;
postorder(root->left);
postorder(root->right);
cout << root->val << " ";
}
int SumOfAllNodes(BinaryTreeNode* root) {
if (root == NULL)
return 0;
return root->val + SumOfAllNodes(root->left) + SumOfAllNodes(root->right);
}
int calculateHeightOfTree(BinaryTreeNode* root) {
if (root == NULL)
return 0;
int leftHeight = calculateHeightOfTree(root->left);
int rightHeight = calculateHeightOfTree(root->right);
return 1 + max(leftHeight, rightHeight);
}
bool isElementExistsInTree(BinaryTreeNode* root, int key) {
if (root == NULL)
return false;
if (root->val == key)
return true;
return isElementExistsInTree(root->left, key) || isElementExistsInTree(root->right, key);
}
int main() {
BinaryTreeNode* root = new BinaryTreeNode(5);
BinaryTreeNode* leftNode = new BinaryTreeNode(2);
BinaryTreeNode* rightNode = new BinaryTreeNode(7);
BinaryTreeNode* leftLeft = new BinaryTreeNode(1);
BinaryTreeNode* leftRight = new BinaryTreeNode(3);
root->left = leftNode;
root->right = rightNode;
leftNode->left = leftLeft;
leftNode->right = leftRight;
cout << "Inorder Traversal: ";
inorder(root);
cout << endl;
cout << "Preorder Traversal: ";
preorder(root);
cout << endl;
cout << "Postorder Traversal: ";
postorder(root);
cout << endl;
cout << "Sum of all nodes: " << SumOfAllNodes(root) << endl;
cout << "Height of tree: " << calculateHeightOfTree(root) << endl;
int searchValue;
cout << "Enter value to search: ";
cin >> searchValue;
if (isElementExistsInTree(root, searchValue))
cout << "Element " << searchValue << " exists in the tree." << endl;
else
cout << "Element " << searchValue << " does not exist in the tree." << endl;
return 0;
}