struct node { int data; struct node* left; struct node* right; }; struct node* newNode(int data) { struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->left = temp->right = NULL; return temp; } struct node* insertNodeInBst(struct node* root, int key) { if (root == NULL) { return newNode(key); } if (key < root->data) { root->left = insertNodeInBst(root->left, key); } else { root->right = insertNodeInBst(root->right, key); } return root; } int level(struct node* root) { if (root == NULL) { return 0; } else { int lLevel = level(root->left); int rLevel = level(root->right); if (lLevel > rLevel) return (lLevel + 1); else return (rLevel + 1); } } void printGivenLevel(struct node* root, int level) { if (root == NULL) return; if (level == 1) printf("%d ", root->data); else if (level > 1) { printGivenLevel(root->left, level - 1); printGivenLevel(root->right, level - 1); } } void reverseLevelOrderTraversal(struct node* root) { int h = level(root); int i; for (i = h; i >= 1; i--) { printGivenLevel(root, i); } } int main() { //Read space separated numbers string rawInput; vector<string> numbers; while (getline(cin, rawInput, ' ')) { numbers.push_back(rawInput); } // Uncomment the below code to Add your inputs here to test without inputting from user /*numbers.push_back("5"); numbers.push_back("4"); numbers.push_back("3"); numbers.push_back("9"); numbers.push_back("1");*/ int key = 0; struct node* root = NULL; while (!numbers.empty()) { string number = numbers.front(); key = atoi(number.c_str()); root = insertNodeInBst(root, key); numbers.erase(numbers.begin()); } reverseLevelOrderTraversal(root); return 0; }
Click like and share to be connected with us @ Facebook.
A place where we love to share and discuss hottest technologies, innovations and researches around.
Print reverse level order traversal of Binary Search Tree
Labels:
Algorithms