Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iostream>
- #include <vector>
- #include <fstream>
- #include <algorithm>
- #include <string>
- #include <climits>
- using namespace std;
- struct Node{
- int data;
- Node *left, *right;
- void createBalancedTree(int n, Node *&curNode, ifstream& inp) {
- int temp;
- if (n > 0) {
- curNode = new Node;
- inp >> temp;
- curNode->data = temp;
- curNode->left = curNode->right = NULL;
- int nLeft = n / 2;
- int nRight = n - nLeft - 1;
- createBalancedTree(nLeft, curNode->left, inp);
- createBalancedTree(nRight, curNode->right, inp);
- }
- }
- void add(int data, Node *&curNode) {
- if (!curNode) {
- curNode = new Node;
- curNode->data = data;
- curNode->left = curNode->right = NULL;
- }
- else if (data < curNode->data)
- add (data, curNode->left);
- else if (data > curNode->data)
- add (data, curNode->right);
- }
- void search(int data, Node *curNode) {
- if (!curNode)
- cout << "Error" << endl;
- else if (data < curNode->data)
- search(data, curNode->left);
- else if (data > curNode->data)
- search(data, curNode->right);
- else
- cout << "Search is successful" << endl;
- }
- void preorder(Node *curNode, ofstream& out) {
- if (curNode) {
- out << curNode->data << ' ';
- preorder(curNode->left, out);
- preorder(curNode->right, out);
- }
- }
- void inorder(Node *curNode, ofstream& out) {
- if (curNode) {
- inorder(curNode->left, out);
- out << curNode->data << ' ';
- inorder(curNode->right, out);
- }
- }
- void postorder(Node *curNode, ofstream& out) {
- if (curNode) {
- postorder(curNode->left, out);
- postorder(curNode->right, out);
- out << curNode->data << ' ';
- }
- }
- int minLeaf(Node *curNode, int &min, ofstream& out) {
- if(curNode) {
- if (curNode->left == NULL && curNode->right == NULL) {
- if (curNode->data < min) {
- min = curNode->data;
- }
- }
- minLeaf(curNode->left, min, out);
- minLeaf(curNode->right, min, out);
- }
- return min;
- }
- int counter(Node *curNode, int &count) {
- if(curNode) {
- if (curNode->left != NULL && curNode->right == NULL) {
- count++;
- }
- counter(curNode->left, count);
- counter(curNode->right, count);
- }
- return count;
- }
- };
- int main() {
- ifstream inp("input.txt");
- ofstream out("output.txt");
- // Node *btree = NULL;
- // int x;
- //Binary Search Tree
- /* while(!inp.eof()) {
- inp >> x;
- btree->add(x, btree);
- }
- btree->preorder(btree, out);
- int min = INT_MAX;
- int minLeaf = btree->minLeaf(btree, min, out);
- out << endl << minLeaf << endl;
- inp.close();
- */
- //Balanced Tree
- Node *tree = NULL;
- int n = 9;
- tree->createBalancedTree(n, tree, inp);
- tree->preorder(tree, out);
- int c = 0;
- c = tree->counter(tree, c);
- out << endl << c << endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment