code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
// C++ program for an efficient solution to check if // a given array can represent Preorder traversal of // a Binary Search Tree #include<bits/stdc++.h> using namespace std; bool canRepresentBST(int pre[], int n) { // Create an empty stack stack<int> s; // Initialize current root as minimum possible // value int root = INT_MIN; // Traverse given array for (int i=0; i<n; i++) { // If we find a node who is on right side // and smaller than root, return false if (pre[i] < root) return false; // If pre[i] is in right subtree of stack top, // Keep removing items smaller than pre[i] // and make the last removed item as new // root. while (!s.empty() && s.top()<pre[i]) { root = s.top(); s.pop(); } // At this point either stack is empty or // pre[i] is smaller than root, push pre[i] s.push(pre[i]); } return true; } // Driver program int main() { int pre1[] = {40, 30, 35, 80, 100}; int n = sizeof(pre1)/sizeof(pre1[0]); canRepresentBST(pre1, n)? cout << "true\n": cout << "false\n"; int pre2[] = {40, 30, 35, 20, 80, 100}; n = sizeof(pre2)/sizeof(pre2[0]); canRepresentBST(pre2, n)? cout << "true\n": cout << "false\n"; return 0; }
linear
linear
// C++ program to illustrate if a given array can represent // a preorder traversal of a BST or not #include <bits/stdc++.h> using namespace std; // We are actually not building the tree void buildBST_helper(int& preIndex, int n, int pre[], int min, int max) { if (preIndex >= n) return; if (min <= pre[preIndex] && pre[preIndex] <= max) { // build node int rootData = pre[preIndex]; preIndex++; // build left subtree buildBST_helper(preIndex, n, pre, min, rootData); // build right subtree buildBST_helper(preIndex, n, pre, rootData, max); } // else // return NULL; } bool canRepresentBST(int arr[], int N) { // code here int min = INT_MIN, max = INT_MAX; int preIndex = 0; buildBST_helper(preIndex, N, arr, min, max); return preIndex == N; } // Driver Code int main() { int preorder1[] = { 2, 4, 3 }; /* 2 \ 4 / 3 */ int n1 = sizeof(preorder1) / sizeof(preorder1[0]); if (canRepresentBST(preorder1, n1)) cout << "\npreorder1 can represent BST"; else cout << "\npreorder1 can not represent BST :("; int preorder2[] = { 5, 3, 4, 1, 6, 10 }; int n2 = sizeof(preorder2) / sizeof(preorder2[0]); /* 5 / \ 3 1 \ / \ 4 6 10 */ if (canRepresentBST(preorder2, n2)) cout << "\npreorder2 can represent BST"; else cout << "\npreorder2 can not represent BST :("; int preorder3[] = { 5, 3, 4, 8, 6, 10 }; int n3 = sizeof(preorder3) / sizeof(preorder3[0]); /* 5 / \ 3 8 \ / \ 4 6 10 */ if (canRepresentBST(preorder3, n3)) cout << "\npreorder3 can represent BST"; else cout << "\npreorder3 can not represent BST :("; return 0; } // This code is contributed by Sourashis Mondal
logn
linear
// A recursive CPP program to find // LCA of two nodes n1 and n2. #include <bits/stdc++.h> using namespace std; class node { public: int data; node *left, *right; }; /* Function to find LCA of n1 and n2. The function assumes that both n1 and n2 are present in BST */ node* lca(node* root, int n1, int n2) { if (root == NULL) return NULL; // If both n1 and n2 are smaller // than root, then LCA lies in left if (root->data > n1 && root->data > n2) return lca(root->left, n1, n2); // If both n1 and n2 are greater than // root, then LCA lies in right if (root->data < n1 && root->data < n2) return lca(root->right, n1, n2); return root; } /* Helper function that allocates a new node with the given data.*/ node* newNode(int data) { node* Node = new node(); Node->data = data; Node->left = Node->right = NULL; return (Node); } /* Driver code*/ int main() { // Let us construct the BST // shown in the above figure node* root = newNode(20); root->left = newNode(8); root->right = newNode(22); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); // Function calls int n1 = 10, n2 = 14; node* t = lca(root, n1, n2); cout << "LCA of " << n1 << " and " << n2 << " is " << t->data << endl; n1 = 14, n2 = 8; t = lca(root, n1, n2); cout << "LCA of " << n1 << " and " << n2 << " is " << t->data << endl; n1 = 10, n2 = 22; t = lca(root, n1, n2); cout << "LCA of " << n1 << " and " << n2 << " is " << t->data << endl; return 0; } // This code is contributed by rathbhupendra
logn
constant
// A recursive CPP program to find // LCA of two nodes n1 and n2. #include <bits/stdc++.h> using namespace std; class node { public: int data; node *left, *right; }; /* Function to find LCA of n1 and n2. The function assumes that both n1 and n2 are present in BST */ node* lca(node* root, int n1, int n2) { while (root != NULL) { // If both n1 and n2 are smaller than root, // then LCA lies in left if (root->data > n1 && root->data > n2) root = root->left; // If both n1 and n2 are greater than root, // then LCA lies in right else if (root->data < n1 && root->data < n2) root = root->right; else break; } return root; } /* Helper function that allocates a new node with the given data.*/ node* newNode(int data) { node* Node = new node(); Node->data = data; Node->left = Node->right = NULL; return (Node); } /* Driver code*/ int main() { // Let us construct the BST // shown in the above figure node* root = newNode(20); root->left = newNode(8); root->right = newNode(22); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); // Function calls int n1 = 10, n2 = 14; node* t = lca(root, n1, n2); cout << "LCA of " << n1 << " and " << n2 << " is " << t->data << endl; n1 = 14, n2 = 8; t = lca(root, n1, n2); cout << "LCA of " << n1 << " and " << n2 << " is " << t->data << endl; n1 = 10, n2 = 22; t = lca(root, n1, n2); cout << "LCA of " << n1 << " and " << n2 << " is " << t->data << endl; return 0; } // This code is contributed by rathbhupendra
constant
constant
#include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: int data; node* left; node* right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; } }; int isBSTUtil(node* node, int min, int max); /* Returns true if the given tree is a binary search tree (efficient version). */ int isBST(node* node) { return (isBSTUtil(node, INT_MIN, INT_MAX)); } /* Returns true if the given tree is a BST and its values are >= min and <= max. */ int isBSTUtil(node* node, int min, int max) { /* an empty tree is BST */ if (node == NULL) return 1; /* false if this node violates the min/max constraint */ if (node->data < min || node->data > max) return 0; /* otherwise check the subtrees recursively, tightening the min or max constraint */ return isBSTUtil(node->left, min, node->data - 1) && // Allow only distinct values isBSTUtil(node->right, node->data + 1, max); // Allow only distinct values } /* Driver code*/ int main() { node* root = new node(4); root->left = new node(2); root->right = new node(5); root->left->left = new node(1); root->left->right = new node(3); // Function call if (isBST(root)) cout << "Is BST"; else cout << "Not a BST"; return 0; } // This code is contributed by rathbhupendra
constant
linear
// C++ program to check if a given tree is BST. #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node *left, *right; Node(int data) { this->data = data; left = right = NULL; } }; bool isBSTUtil(struct Node* root, Node*& prev) { // traverse the tree in inorder fashion and // keep track of prev node if (root) { if (!isBSTUtil(root->left, prev)) return false; // Allows only distinct valued nodes if (prev != NULL && root->data <= prev->data) return false; prev = root; return isBSTUtil(root->right, prev); } return true; } bool isBST(Node* root) { Node* prev = NULL; return isBSTUtil(root, prev); } /* Driver code*/ int main() { struct Node* root = new Node(3); root->left = new Node(2); root->right = new Node(5); root->left->left = new Node(1); root->left->right = new Node(4); // Function call if (isBST(root)) cout << "Is BST"; else cout << "Not a BST"; return 0; }
logn
linear
// A C++ program to check for Identical // BSTs without building the trees #include <bits/stdc++.h> using namespace std; /* The main function that checks if two arrays a[] and b[] of size n construct same BST. The two values 'min' and 'max' decide whether the call is made for left subtree or right subtree of a parent element. The indexes i1 and i2 are the indexes in (a[] and b[]) after which we search the left or right child. Initially, the call is made for INT_MIN and INT_MAX as 'min' and 'max' respectively, because root has no parent. i1 and i2 are just after the indexes of the parent element in a[] and b[]. */ bool isSameBSTUtil(int a[], int b[], int n, int i1, int i2, int min, int max) { int j, k; /* Search for a value satisfying the constraints of min and max in a[] and b[]. If the parent element is a leaf node then there must be some elements in a[] and b[] satisfying constraint. */ for (j = i1; j < n; j++) if (a[j] > min && a[j] < max) break; for (k = i2; k < n; k++) if (b[k] > min && b[k] < max) break; /* If the parent element is leaf in both arrays */ if (j == n && k == n) return true; /* Return false if any of the following is true a) If the parent element is leaf in one array, but non-leaf in other. b) The elements satisfying constraints are not same. We either search for left child or right child of the parent element (decided by min and max values). The child found must be same in both arrays */ if (((j == n) ^ (k == n)) || a[j] != b[k]) return false; /* Make the current child as parent and recursively check for left and right subtrees of it. Note that we can also pass a[k] in place of a[j] as they are both are same */ return isSameBSTUtil(a, b, n, j + 1, k + 1, a[j], max) && // Right Subtree isSameBSTUtil(a, b, n, j + 1, k + 1, min, a[j]); // Left Subtree } // A wrapper over isSameBSTUtil() bool isSameBST(int a[], int b[], int n) { return isSameBSTUtil(a, b, n, 0, 0, INT_MIN, INT_MAX); } // Driver code int main() { int a[] = { 8, 3, 6, 1, 4, 7, 10, 14, 13 }; int b[] = { 8, 10, 14, 3, 6, 4, 1, 7, 13 }; int n = sizeof(a) / sizeof(a[0]); if (isSameBST(a, b, n)) { cout << "BSTs are same"; } else { cout << "BSTs not same"; } return 0; } // This code is contributed by rathbhupendra
linear
quadratic
// CPP code for finding K-th largest Node using O(1) // extra memory and reverse Morris traversal. #include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node *left, *right; }; // helper function to create a new Node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->right = temp->left = NULL; return temp; } Node* KthLargestUsingMorrisTraversal(Node* root, int k) { Node* curr = root; Node* Klargest = NULL; // count variable to keep count of visited Nodes int count = 0; while (curr != NULL) { // if right child is NULL if (curr->right == NULL) { // first increment count and check if count = k if (++count == k) Klargest = curr; // otherwise move to the left child curr = curr->left; } else { // find inorder successor of current Node Node* succ = curr->right; while (succ->left != NULL && succ->left != curr) succ = succ->left; if (succ->left == NULL) { // set left child of successor to the // current Node succ->left = curr; // move current to its right curr = curr->right; } // restoring the tree back to original binary // search tree removing threaded links else { succ->left = NULL; if (++count == k) Klargest = curr; // move current to its left child curr = curr->left; } } } return Klargest; } int main() { // Your C++ Code /* Constructed binary tree is 4 / \ 2 7 / \ / \ 1 3 6 10 */ Node* root = newNode(4); root->left = newNode(2); root->right = newNode(7); root->left->left = newNode(1); root->left->right = newNode(3); root->right->left = newNode(6); root->right->right = newNode(10); cout << "Finding K-th largest Node in BST : " << KthLargestUsingMorrisTraversal(root, 2)->data; return 0; }
constant
linear
// C++ program to find k'th largest element in BST #include<bits/stdc++.h> using namespace std; // A BST node struct Node { int key; Node *left, *right; }; // A function to find int KSmallestUsingMorris(Node *root, int k) { // Count to iterate over elements till we // get the kth smallest number int count = 0; int ksmall = INT_MIN; // store the Kth smallest Node *curr = root; // to store the current node while (curr != NULL) { // Like Morris traversal if current does // not have left child rather than printing // as we did in inorder, we will just // increment the count as the number will // be in an increasing order if (curr->left == NULL) { count++; // if count is equal to K then we found the // kth smallest, so store it in ksmall if (count==k) ksmall = curr->key; // go to current's right child curr = curr->right; } else { // we create links to Inorder Successor and // count using these links Node *pre = curr->left; while (pre->right != NULL && pre->right != curr) pre = pre->right; // building links if (pre->right==NULL) { //link made to Inorder Successor pre->right = curr; curr = curr->left; } // While breaking the links in so made temporary // threaded tree we will check for the K smallest // condition else { // Revert the changes made in if part (break link // from the Inorder Successor) pre->right = NULL; count++; // If count is equal to K then we found // the kth smallest and so store it in ksmall if (count==k) ksmall = curr->key; curr = curr->right; } } } return ksmall; //return the found value } // A utility function to create a new BST node Node *newNode(int item) { Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp; } /* A utility function to insert a new node with given key in BST */ Node* insert(Node* node, int key) { /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node; } // Driver Program to test above functions int main() { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); for (int k=1; k<=7; k++) cout << KSmallestUsingMorris(root, k) << " "; return 0; }
constant
linear
// C++ program to check if a given array is sorted // or not. #include<bits/stdc++.h> using namespace std; // Function that returns true if array is Inorder // traversal of any Binary Search Tree or not. bool isInorder(int arr[], int n) { // Array has one or no element if (n == 0 || n == 1) return true; for (int i = 1; i < n; i++) // Unsorted pair found if (arr[i-1] > arr[i]) return false; // No unsorted pair found return true; } // Driver code int main() { int arr[] = { 19, 23, 25, 30, 45 }; int n = sizeof(arr)/sizeof(arr[0]); if (isInorder(arr, n)) cout << "Yesn"; else cout << "Non"; return 0; }
constant
linear
// CPP program to check if two BSTs contains // same set of elements #include<bits/stdc++.h> using namespace std; // BST Node struct Node { int data; struct Node* left; struct Node* right; }; // Utility function to create new Node Node* newNode(int val) { Node* temp = new Node; temp->data = val; temp->left = temp->right = NULL; return temp; } // function to insert elements of the // tree to map m void insertToHash(Node* root, unordered_set<int> &s) { if (!root) return; insertToHash(root->left, s); s.insert(root->data); insertToHash(root->right, s); } // function to check if the two BSTs contain // same set of elements bool checkBSTs(Node* root1, Node* root2) { // Base cases if (!root1 && !root2) return true; if ((root1 && !root2) || (!root1 && root2)) return false; // Create two hash sets and store // elements both BSTs in them. unordered_set<int> s1, s2; insertToHash(root1, s1); insertToHash(root2, s2); // Return true if both hash sets // contain same elements. return (s1 == s2); } // Driver program to check above functions int main() { // First BST Node* root1 = newNode(15); root1->left = newNode(10); root1->right = newNode(20); root1->left->left = newNode(5); root1->left->right = newNode(12); root1->right->right = newNode(25); // Second BST Node* root2 = newNode(15); root2->left = newNode(12); root2->right = newNode(20); root2->left->left = newNode(5); root2->left->left->right = newNode(10); root2->right->right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) cout << "YES"; else cout << "NO"; return 0; }
linear
linear
// CPP program to check if two BSTs contains // same set of elements #include<bits/stdc++.h> using namespace std; // BST Node struct Node { int data; struct Node* left; struct Node* right; }; // Utility function to create new Node Node* newNode(int val) { Node* temp = new Node; temp->data = val; temp->left = temp->right = NULL; return temp; } // function to insert elements of the // tree to map m void storeInorder(Node* root, vector<int> &v) { if (!root) return; storeInorder(root->left, v); v.push_back(root->data); storeInorder(root->right, v); } // function to check if the two BSTs contain // same set of elements bool checkBSTs(Node* root1, Node* root2) { // Base cases if (!root1 && !root2) return true; if ((root1 && !root2) || (!root1 && root2)) return false; // Create two vectors and store // inorder traversals of both BSTs // in them. vector<int> v1, v2; storeInorder(root1, v1); storeInorder(root2, v2); // Return true if both vectors are // identical return (v1 == v2); } // Driver program to check above functions int main() { // First BST Node* root1 = newNode(15); root1->left = newNode(10); root1->right = newNode(20); root1->left->left = newNode(5); root1->left->right = newNode(12); root1->right->right = newNode(25); // Second BST Node* root2 = newNode(15); root2->left = newNode(12); root2->right = newNode(20); root2->left->left = newNode(5); root2->left->left->right = newNode(10); root2->right->right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) cout << "YES"; else cout << "NO"; return 0; }
linear
linear
// C++ implementation to count pairs from two // BSTs whose sum is equal to a given value x #include <bits/stdc++.h> using namespace std; // structure of a node of BST struct Node { int data; Node* left, *right; }; // function to create and return a node of BST Node* getNode(int data) { // allocate space for the node Node* new_node = (Node*)malloc(sizeof(Node)); // put in the data new_node->data = data; new_node->left = new_node->right = NULL; } // function to count pairs from two BSTs // whose sum is equal to a given value x int countPairs(Node* root1, Node* root2, int x) { // if either of the tree is empty if (root1 == NULL || root2 == NULL) return 0; // stack 'st1' used for the inorder // traversal of BST 1 // stack 'st2' used for the reverse // inorder traversal of BST 2 stack<Node*> st1, st2; Node* top1, *top2; int count = 0; // the loop will break when either of two // traversals gets completed while (1) { // to find next node in inorder // traversal of BST 1 while (root1 != NULL) { st1.push(root1); root1 = root1->left; } // to find next node in reverse // inorder traversal of BST 2 while (root2 != NULL) { st2.push(root2); root2 = root2->right; } // if either gets empty then corresponding // tree traversal is completed if (st1.empty() || st2.empty()) break; top1 = st1.top(); top2 = st2.top(); // if the sum of the node's is equal to 'x' if ((top1->data + top2->data) == x) { // increment count count++; // pop nodes from the respective stacks st1.pop(); st2.pop(); // insert next possible node in the // respective stacks root1 = top1->right; root2 = top2->left; } // move to next possible node in the // inorder traversal of BST 1 else if ((top1->data + top2->data) < x) { st1.pop(); root1 = top1->right; } // move to next possible node in the // reverse inorder traversal of BST 2 else { st2.pop(); root2 = top2->left; } } // required count of pairs return count; } // Driver program to test above int main() { // formation of BST 1 Node* root1 = getNode(5); /* 5 */ root1->left = getNode(3); /* / \ */ root1->right = getNode(7); /* 3 7 */ root1->left->left = getNode(2); /* / \ / \ */ root1->left->right = getNode(4); /* 2 4 6 8 */ root1->right->left = getNode(6); root1->right->right = getNode(8); // formation of BST 2 Node* root2 = getNode(10); /* 10 */ root2->left = getNode(6); /* / \ */ root2->right = getNode(15); /* 6 15 */ root2->left->left = getNode(3); /* / \ / \ */ root2->left->right = getNode(8); /* 3 8 11 18 */ root2->right->left = getNode(11); root2->right->right = getNode(18); int x = 16; cout << "Pairs = " << countPairs(root1, root2, x); return 0; }
logn
linear
/* C++ program to find the median of BST in O(n) time and O(1) space*/ #include<bits/stdc++.h> using namespace std; /* A binary search tree Node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left, *right; }; // A utility function to create a new BST node struct Node *newNode(int item) { struct Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp; } /* A utility function to insert a new node with given key in BST */ struct Node* insert(struct Node* node, int key) { /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->data) node->left = insert(node->left, key); else if (key > node->data) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node; } /* Function to count nodes in a binary search tree using Morris Inorder traversal*/ int counNodes(struct Node *root) { struct Node *current, *pre; // Initialise count of nodes as 0 int count = 0; if (root == NULL) return count; current = root; while (current != NULL) { if (current->left == NULL) { // Count node if its left is NULL count++; // Move to its right current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if(pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre->right = NULL; // Increment count if the current // node is to be visited count++; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return count; } /* Function to find median in O(n) time and O(1) space using Morris Inorder traversal*/ int findMedian(struct Node *root) { if (root == NULL) return 0; int count = counNodes(root); int currCount = 0; struct Node *current = root, *pre, *prev; while (current != NULL) { if (current->left == NULL) { // count current node currCount++; // check if current node is the median // Odd case if (count % 2 != 0 && currCount == (count+1)/2) return current->data; // Even case else if (count % 2 == 0 && currCount == (count/2)+1) return (prev->data + current->data)/2; // Update prev for even no. of nodes prev = current; //Move to the right current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if (pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre->right = NULL; prev = pre; // Count current node currCount++; // Check if the current node is the median if (count % 2 != 0 && currCount == (count+1)/2 ) return current->data; else if (count%2==0 && currCount == (count/2)+1) return (prev->data+current->data)/2; // update prev node for the case of even // no. of nodes prev = current; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ } /* Driver program to test above functions*/ int main() { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ struct Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); cout << "\nMedian of BST is " << findMedian(root); return 0; }
constant
linear
// C++ program to find largest BST in a // Binary Tree. #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Information to be returned by every // node in bottom up traversal. struct Info { // Size of subtree int sz; // Min value in subtree int max; // Max value in subtree int min; // Size of largest BST which // is subtree of current node int ans; // If subtree is BST bool isBST; }; // Returns Information about subtree. The // Information also includes size of largest // subtree which is a BST. Info largestBSTBT(Node* root) { // Base cases : When tree is empty or it has // one child. if (root == NULL) return { 0, INT_MIN, INT_MAX, 0, true }; if (root->left == NULL && root->right == NULL) return { 1, root->data, root->data, 1, true }; // Recur for left subtree and right subtrees Info l = largestBSTBT(root->left); Info r = largestBSTBT(root->right); // Create a return variable and initialize its // size. Info ret; ret.sz = (1 + l.sz + r.sz); // If whole tree rooted under current root is // BST. if (l.isBST && r.isBST && l.max < root->data && r.min > root->data) { ret.min = min(l.min, root->data); ret.max = max(r.max, root->data); // Update answer for tree rooted under // current 'root' ret.ans = l.ans + r.ans + 1; ret.isBST = true; return ret; } // If whole tree is not BST, return maximum // of left and right subtrees ret.ans = max(l.ans, r.ans); ret.isBST = false; return ret; } /* Driver program to test above functions*/ int main() { /* Let us construct the following Tree 60 / \ 65 70 / 50 */ struct Node* root = newNode(60); root->left = newNode(65); root->right = newNode(70); root->left->left = newNode(50); printf(" Size of the largest BST is %d\n", largestBSTBT(root).ans); return 0; } // This code is contributed by Vivek Garg in a // comment on below set 1. // www.geeksforgeeks.org/find-the-largest-subtree-in-a-tree-that-is-also-a-bst/ // This code is updated by Naman Sharma
linear
linear
// A C++ program to remove BST keys // outside the given range #include<bits/stdc++.h> using namespace std; // A BST node has key, and left and right pointers struct node { int key; struct node *left; struct node *right; }; // Removes all nodes having value outside the // given range and returns the root of modified tree node* removeOutsideRange(node *root, int min, int max) { // Base Case if (root == NULL) return NULL; // First fix the left and right subtrees of root root->left = removeOutsideRange(root->left, min, max); root->right = removeOutsideRange(root->right, min, max); // Now fix the root. There are 2 possible cases // for root 1.a) Root's key is smaller than min // value (root is not in range) if (root->key < min) { node *rChild = root->right; delete root; return rChild; } // 1.b) Root's key is greater than max value // (root is not in range) if (root->key > max) { node *lChild = root->left; delete root; return lChild; } // 2. Root is in range return root; } // A utility function to create a new BST // node with key as given num node* newNode(int num) { node* temp = new node; temp->key = num; temp->left = temp->right = NULL; return temp; } // A utility function to insert a given key to BST node* insert(node* root, int key) { if (root == NULL) return newNode(key); if (root->key > key) root->left = insert(root->left, key); else root->right = insert(root->right, key); return root; } // Utility function to traverse the binary // tree after conversion void inorderTraversal(node* root) { if (root) { inorderTraversal( root->left ); cout << root->key << " "; inorderTraversal( root->right ); } } // Driver program to test above functions int main() { node* root = NULL; root = insert(root, 6); root = insert(root, -13); root = insert(root, 14); root = insert(root, -8); root = insert(root, 15); root = insert(root, 13); root = insert(root, 7); cout << "Inorder traversal of the given tree is: "; inorderTraversal(root); root = removeOutsideRange(root, -10, 13); cout << "\nInorder traversal of the modified tree is: "; inorderTraversal(root); return 0; }
constant
linear
// C++ program to print BST in given range #include<bits/stdc++.h> using namespace std; /* A tree node structure */ class node { public: int data; node *left; node *right; }; /* The functions prints all the keys which in the given range [k1..k2]. The function assumes than k1 < k2 */ void Print(node *root, int k1, int k2) { /* base case */ if ( NULL == root ) return; /* Since the desired o/p is sorted, recurse for left subtree first If root->data is greater than k1, then only we can get o/p keys in left subtree */ if ( k1 < root->data ) Print(root->left, k1, k2); /* if root's data lies in range, then prints root's data */ if ( k1 <= root->data && k2 >= root->data ) cout<<root->data<<" "; /* recursively call the right subtree */ Print(root->right, k1, k2); } /* Utility function to create a new Binary Tree node */ node* newNode(int data) { node *temp = new node(); temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } /* Driver code */ int main() { node *root = new node(); int k1 = 10, k2 = 25; /* Constructing tree given in the above figure */ root = newNode(20); root->left = newNode(8); root->right = newNode(22); root->left->left = newNode(4); root->left->right = newNode(12); Print(root, k1, k2); return 0; } // This code is contributed by rathbhupendra
logn
linear
// CPP code to print BST keys in given Range in // constant space using Morris traversal. #include <bits/stdc++.h> using namespace std; struct node { int data; struct node *left, *right; }; // Function to print the keys in range void RangeTraversal(node* root, int n1, int n2) { if (!root) return; node* curr = root; while (curr) { if (curr->left == NULL) { // check if current node // lies between n1 and n2 if (curr->data <= n2 && curr->data >= n1) { cout << curr->data << " "; } curr = curr->right; } else { node* pre = curr->left; // finding the inorder predecessor- // inorder predecessor is the right // most in left subtree or the left // child, i.e in BST it is the // maximum(right most) in left subtree. while (pre->right != NULL && pre->right != curr) pre = pre->right; if (pre->right == NULL) { pre->right = curr; curr = curr->left; } else { pre->right = NULL; // check if current node lies // between n1 and n2 if (curr->data <= n2 && curr->data >= n1) { cout << curr->data << " "; } curr = curr->right; } } } } // Helper function to create a new node node* newNode(int data) { node* temp = new node; temp->data = data; temp->right = temp->left = NULL; return temp; } // Driver Code int main() { /* Constructed binary tree is 4 / \ 2 7 / \ / \ 1 3 6 10 */ node* root = newNode(4); root->left = newNode(2); root->right = newNode(7); root->left->left = newNode(1); root->left->right = newNode(3); root->right->left = newNode(6); root->right->right = newNode(10); RangeTraversal(root, 4, 12); return 0; }
constant
linear
// C++ program to count BST nodes within a given range #include<bits/stdc++.h> using namespace std; // A BST node struct node { int data; struct node* left, *right; }; // Utility function to create new node node *newNode(int data) { node *temp = new node; temp->data = data; temp->left = temp->right = NULL; return (temp); } // Returns count of nodes in BST in range [low, high] int getCount(node *root, int low, int high) { // Base case if (!root) return 0; // Special Optional case for improving efficiency if (root->data == high && root->data == low) return 1; // If current node is in range, then include it in count and // recur for left and right children of it if (root->data <= high && root->data >= low) return 1 + getCount(root->left, low, high) + getCount(root->right, low, high); // If current node is smaller than low, then recur for right // child else if (root->data < low) return getCount(root->right, low, high); // Else recur for left child else return getCount(root->left, low, high); } // Driver program int main() { // Let us construct the BST shown in the above figure node *root = newNode(10); root->left = newNode(5); root->right = newNode(50); root->left->left = newNode(1); root->right->left = newNode(40); root->right->right = newNode(100); /* Let us constructed BST shown in above example 10 / \ 5 50 / / \ 1 40 100 */ int l = 5; int h = 45; cout << "Count of nodes between [" << l << ", " << h << "] is " << getCount(root, l, h); return 0; }
linear
constant
// c++ program to find Sum Of All Elements smaller // than or equal to Kth Smallest Element In BST #include <bits/stdc++.h> using namespace std; /* Binary tree Node */ struct Node { int data; Node* left, * right; }; // utility function new Node of BST struct Node *createNode(int data) { Node * new_Node = new Node; new_Node->left = NULL; new_Node->right = NULL; new_Node->data = data; return new_Node; } // A utility function to insert a new Node // with given key in BST and also maintain lcount ,Sum struct Node * insert(Node *root, int key) { // If the tree is empty, return a new Node if (root == NULL) return createNode(key); // Otherwise, recur down the tree if (root->data > key) root->left = insert(root->left, key); else if (root->data < key) root->right = insert(root->right, key); // return the (unchanged) Node pointer return root; } // function return sum of all element smaller than // and equal to Kth smallest element int ksmallestElementSumRec(Node *root, int k, int &count) { // Base cases if (root == NULL) return 0; if (count > k) return 0; // Compute sum of elements in left subtree int res = ksmallestElementSumRec(root->left, k, count); if (count >= k) return res; // Add root's data res += root->data; // Add current Node count++; if (count >= k) return res; // If count is less than k, return right subtree Nodes return res + ksmallestElementSumRec(root->right, k, count); } // Wrapper over ksmallestElementSumRec() int ksmallestElementSum(struct Node *root, int k) { int count = 0; return ksmallestElementSumRec(root, k, count); } /* Driver program to test above functions */ int main() { /* 20 / \ 8 22 / \ 4 12 / \ 10 14 */ Node *root = NULL; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; cout << ksmallestElementSum(root, k) <<endl; return 0; }
logn
constant
// C++ program to find predecessor and successor in a BST #include <iostream> using namespace std; // BST Node struct Node { int key; struct Node *left, *right; }; // This function finds predecessor and successor of key in BST. // It sets pre and suc as predecessor and successor respectively void findPreSuc(Node* root, Node*& pre, Node*& suc, int key) { // Base case if (root == NULL) return ; // If key is present at root if (root->key == key) { // the maximum value in left subtree is predecessor if (root->left != NULL) { Node* tmp = root->left; while (tmp->right) tmp = tmp->right; pre = tmp ; } // the minimum value in right subtree is successor if (root->right != NULL) { Node* tmp = root->right ; while (tmp->left) tmp = tmp->left ; suc = tmp ; } return ; } // If key is smaller than root's key, go to left subtree if (root->key > key) { suc = root ; findPreSuc(root->left, pre, suc, key) ; } else // go to right subtree { pre = root ; findPreSuc(root->right, pre, suc, key) ; } } // A utility function to create a new BST node Node *newNode(int item) { Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp; } /* A utility function to insert a new node with given key in BST */ Node* insert(Node* node, int key) { if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); return node; } // Driver program to test above function int main() { int key = 65; //Key to be searched in BST /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); Node* pre = NULL, *suc = NULL; findPreSuc(root, pre, suc, key); if (pre != NULL) cout << "Predecessor is " << pre->key << endl; else cout << "No Predecessor"; if (suc != NULL) cout << "Successor is " << suc->key; else cout << "No Successor"; return 0; }
constant
logn
// CPP code for inorder successor // and predecessor of tree #include<iostream> #include<stdlib.h> using namespace std; struct Node { int data; Node* left,*right; }; // Function to return data Node* getnode(int info) { Node* p = (Node*)malloc(sizeof(Node)); p->data = info; p->right = NULL; p->left = NULL; return p; } /* since inorder traversal results in ascending order visit to node , we can store the values of the largest no which is smaller than a (predecessor) and smallest no which is large than a (successor) using inorder traversal */ void find_p_s(Node* root,int a, Node** p, Node** q) { // If root is null return if(!root) return ; // traverse the left subtree find_p_s(root->left, a, p, q); // root data is greater than a if(root&&root->data > a) { // q stores the node whose data is greater // than a and is smaller than the previously // stored data in *q which is successor if((!*q) || (*q) && (*q)->data > root->data) *q = root; } // if the root data is smaller than // store it in p which is predecessor else if(root && root->data < a) { *p = root; } // traverse the right subtree find_p_s(root->right, a, p, q); } // Driver code int main() { Node* root1 = getnode(50); root1->left = getnode(20); root1->right = getnode(60); root1->left->left = getnode(10); root1->left->right = getnode(30); root1->right->left = getnode(55); root1->right->right = getnode(70); Node* p = NULL, *q = NULL; find_p_s(root1, 55, &p, &q); if(p) cout << p->data; if(q) cout << " " << q->data; return 0; }
linear
linear
// C++ program to find predecessor // and successor in a BST #include <bits/stdc++.h> using namespace std; // BST Node struct Node { int key; struct Node *left, *right; }; // Function that finds predecessor and successor of key in BST. void findPreSuc(Node* root, Node*& pre, Node*& suc, int key) { if (root == NULL) return; // Search for given key in BST. while (root != NULL) { // If root is given key. if (root->key == key) { // the minimum value in right subtree // is successor. if (root->right) { suc = root->right; while (suc->left) suc = suc->left; } // the maximum value in left subtree // is predecessor. if (root->left) { pre = root->left; while (pre->right) pre = pre->right; } return; } // If key is greater than root, then // key lies in right subtree. Root // could be predecessor if left // subtree of key is null. else if (root->key < key) { pre = root; root = root->right; } // If key is smaller than root, then // key lies in left subtree. Root // could be successor if right // subtree of key is null. else { suc = root; root = root->left; } } } // A utility function to create a new BST node Node* newNode(int item) { Node* temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp; } // A utility function to insert // a new node with given key in BST Node* insert(Node* node, int key) { if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); return node; } // Driver program to test above function int main() { int key = 65; // Key to be searched in BST /* Let us create following BST 50 / \ / \ 30 70 / \ / \ / \ / \ 20 40 60 80 */ Node* root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); Node *pre = NULL, *suc = NULL; findPreSuc(root, pre, suc, key); if (pre != NULL) cout << "Predecessor is " << pre->key << endl; else cout << "-1"; if (suc != NULL) cout << "Successor is " << suc->key; else cout << "-1"; return 0; }
constant
linear
// CPP program to find a pair with // given sum using hashing #include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node *left, *right; }; Node* NewNode(int data) { Node* temp = (Node*)malloc(sizeof(Node)); temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } Node* insert(Node* root, int key) { if (root == NULL) return NewNode(key); if (key < root->data) root->left = insert(root->left, key); else root->right = insert(root->right, key); return root; } bool findpairUtil(Node* root, int sum, unordered_set<int>& set) { if (root == NULL) return false; if (findpairUtil(root->left, sum, set)) return true; if (set.find(sum - root->data) != set.end()) { cout << "Pair is found (" << sum - root->data << ", " << root->data << ")" << endl; return true; } else set.insert(root->data); return findpairUtil(root->right, sum, set); } void findPair(Node* root, int sum) { unordered_set<int> set; if (!findpairUtil(root, sum, set)) cout << "Pairs do not exit" << endl; } // Driver code int main() { Node* root = NULL; root = insert(root, 15); root = insert(root, 10); root = insert(root, 20); root = insert(root, 8); root = insert(root, 12); root = insert(root, 16); root = insert(root, 25); root = insert(root, 10); int sum = 28; findPair(root, sum); return 0; }
linear
linear
// C++ program to find pairs with given sum such // that one element of pair exists in one BST and // other in other BST. #include<bits/stdc++.h> using namespace std; // A binary Tree node struct Node { int data; struct Node *left, *right; }; // A utility function to create a new BST node // with key as given num struct Node* newNode(int num) { struct Node* temp = new Node; temp->data = num; temp->left = temp->right = NULL; return temp; } // A utility function to insert a given key to BST Node* insert(Node* root, int key) { if (root == NULL) return newNode(key); if (root->data > key) root->left = insert(root->left, key); else root->right = insert(root->right, key); return root; } // store storeInorder traversal in auxiliary array void storeInorder(Node *ptr, vector<int> &vect) { if (ptr==NULL) return; storeInorder(ptr->left, vect); vect.push_back(ptr->data); storeInorder(ptr->right, vect); } // Function to find pair for given sum in different bst // vect1[] --> stores storeInorder traversal of first bst // vect2[] --> stores storeInorder traversal of second bst void pairSumUtil(vector<int> &vect1, vector<int> &vect2, int sum) { // Initialize two indexes to two different corners // of two vectors. int left = 0; int right = vect2.size() - 1; // find pair by moving two corners. while (left < vect1.size() && right >= 0) { // If we found a pair if (vect1[left] + vect2[right] == sum) { cout << "(" << vect1[left] << ", " << vect2[right] << "), "; left++; right--; } // If sum is more, move to higher value in // first vector. else if (vect1[left] + vect2[right] < sum) left++; // If sum is less, move to lower value in // second vector. else right--; } } // Prints all pairs with given "sum" such that one // element of pair is in tree with root1 and other // node is in tree with root2. void pairSum(Node *root1, Node *root2, int sum) { // Store inorder traversals of two BSTs in two // vectors. vector<int> vect1, vect2; storeInorder(root1, vect1); storeInorder(root2, vect2); // Now the problem reduces to finding a pair // with given sum such that one element is in // vect1 and other is in vect2. pairSumUtil(vect1, vect2, sum); } // Driver program to run the case int main() { // first BST struct Node* root1 = NULL; root1 = insert(root1, 8); root1 = insert(root1, 10); root1 = insert(root1, 3); root1 = insert(root1, 6); root1 = insert(root1, 1); root1 = insert(root1, 5); root1 = insert(root1, 7); root1 = insert(root1, 14); root1 = insert(root1, 13); // second BST struct Node* root2 = NULL; root2 = insert(root2, 5); root2 = insert(root2, 18); root2 = insert(root2, 2); root2 = insert(root2, 1); root2 = insert(root2, 3); root2 = insert(root2, 4); int sum = 10; pairSum(root1, root2, sum); return 0; }
linear
linear
// Recursive C++ program to find key closest to k // in given Binary Search Tree. #include<bits/stdc++.h> using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */ struct Node { int key; struct Node* left, *right; }; /* Utility that allocates a new node with the given key and NULL left and right pointers. */ struct Node* newnode(int key) { struct Node* node = new (struct Node); node->key = key; node->left = node->right = NULL; return (node); } // Function to find node with minimum absolute // difference with given K // min_diff --> minimum difference till now // min_diff_key --> node having minimum absolute // difference with K void maxDiffUtil(struct Node *ptr, int k, int &min_diff, int &min_diff_key) { if (ptr == NULL) return ; // If k itself is present if (ptr->key == k) { min_diff_key = k; return; } // update min_diff and min_diff_key by checking // current node value if (min_diff > abs(ptr->key - k)) { min_diff = abs(ptr->key - k); min_diff_key = ptr->key; } // if k is less than ptr->key then move in // left subtree else in right subtree if (k < ptr->key) maxDiffUtil(ptr->left, k, min_diff, min_diff_key); else maxDiffUtil(ptr->right, k, min_diff, min_diff_key); } // Wrapper over maxDiffUtil() int maxDiff(Node *root, int k) { // Initialize minimum difference int min_diff = INT_MAX, min_diff_key = -1; // Find value of min_diff_key (Closest key // in tree with k) maxDiffUtil(root, k, min_diff, min_diff_key); return min_diff_key; } // Driver program to run the case int main() { struct Node *root = newnode(9); root->left = newnode(4); root->right = newnode(17); root->left->left = newnode(3); root->left->right = newnode(6); root->left->right->left = newnode(5); root->left->right->right = newnode(7); root->right->right = newnode(22); root->right->right->left = newnode(20); int k = 18; cout << maxDiff(root, k); return 0; }
constant
constant
// C++ program to find largest BST in a Binary Tree. #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; Node(int val) { this->data = val; left = NULL; right = NULL; } }; vector<int> largestBSTBT(Node* root) { // Base cases : When tree is empty or it has one child. if (root == NULL) return {INT_MAX, INT_MIN, 0}; if (root->left == NULL && root->right == NULL) return {root->data, root->data, 1}; // Recur for left subtree and right subtrees vector<int> left = largestBSTBT(root->left); vector<int> right = largestBSTBT(root->right); // Create a return variable and initialize its size. vector<int> ans(3, 0); // If whole tree rooted under current root is BST. if ((left[1] < root->data) && (right[0] > root->data)) { ans[0] = min(left[0], min(right[0], root->data)); ans[1] = max(right[1], max(left[1], root->data)); // Update answer for tree rooted under current 'root' ans[2] = 1 + left[2] + right[2]; return ans; } // If whole tree is not BST, return maximum of left and right subtrees ans[0] = INT_MIN; ans[1] = INT_MAX; ans[2] = max(left[2], right[2]); return ans; } int largestBSTBTutil(Node *root) { return largestBSTBT(root)[2]; } // Driver Function int main() { /* Let us construct the following Tree 50 / \ 75 45 / 45 */ struct Node *root = new Node(50); root->left = new Node(75); root->right = new Node(45); root->left->left = new Node(40); printf(" Size of the largest BST is %d\n", largestBSTBTutil(root)); return 0; } // This Code is cuntributed by Ajay Makvana
linear
linear
// C++ program to add all greater // values in every node of BST #include <bits/stdc++.h> using namespace std; class Node { public: int data; Node *left, *right; }; // A utility function to create // a new BST node Node* newNode(int item) { Node* temp = new Node(); temp->data = item; temp->left = temp->right = NULL; return temp; } // Recursive function to add all // greater values in every node void modifyBSTUtil(Node* root, int* sum) { // Base Case if (root == NULL) return; // Recur for right subtree modifyBSTUtil(root->right, sum); // Now *sum has sum of nodes // in right subtree, add // root->data to sum and // update root->data *sum = *sum + root->data; root->data = *sum; // Recur for left subtree modifyBSTUtil(root->left, sum); } // A wrapper over modifyBSTUtil() void modifyBST(Node* root) { int sum = 0; modifyBSTUtil(root, ∑); } // A utility function to do // inorder traversal of BST void inorder(Node* root) { if (root != NULL) { inorder(root->left); cout << root->data << " "; inorder(root->right); } } /* A utility function to insert a new node with given data in BST */ Node* insert(Node* node, int data) { /* If the tree is empty, return a new node */ if (node == NULL) return newNode(data); /* Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node; } // Driver code int main() { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node* root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); modifyBST(root); // print inorder traversal of the modified BST inorder(root); return 0; } // This code is contributed by rathbhupendra
constant
linear
/* C++ program to convert a Binary Tree to Threaded Tree */ #include <bits/stdc++.h> using namespace std; /* Structure of a node in threaded binary tree */ struct Node { int key; Node *left, *right; // Used to indicate whether the right pointer is a // normal right pointer or a pointer to inorder // successor. bool isThreaded; }; // Helper function to put the Nodes in inorder into queue void populateQueue(Node* root, std::queue<Node*>* q) { if (root == NULL) return; if (root->left) populateQueue(root->left, q); q->push(root); if (root->right) populateQueue(root->right, q); } // Function to traverse queue, and make tree threaded void createThreadedUtil(Node* root, std::queue<Node*>* q) { if (root == NULL) return; if (root->left) createThreadedUtil(root->left, q); q->pop(); if (root->right) createThreadedUtil(root->right, q); // If right pointer is NULL, link it to the // inorder successor and set 'isThreaded' bit. else { root->right = q->front(); root->isThreaded = true; } } // This function uses populateQueue() and // createThreadedUtil() to convert a given binary tree // to threaded tree. void createThreaded(Node* root) { // Create a queue to store inorder traversal std::queue<Node*> q; // Store inorder traversal in queue populateQueue(root, &q); // Link NULL right pointers to inorder successor createThreadedUtil(root, &q); } // A utility function to find leftmost node in a binary // tree rooted with 'root'. This function is used in // inOrder() Node* leftMost(Node* root) { while (root != NULL && root->left != NULL) root = root->left; return root; } // Function to do inorder traversal of a threaded binary // tree void inOrder(Node* root) { if (root == NULL) return; // Find the leftmost node in Binary Tree Node* cur = leftMost(root); while (cur != NULL) { cout << cur->key << " "; // If this Node is a thread Node, then go to // inorder successor if (cur->isThreaded) cur = cur->right; else // Else go to the leftmost child in right // subtree cur = leftMost(cur->right); } } // A utility function to create a new node Node* newNode(int key) { Node* temp = new Node; temp->left = temp->right = NULL; temp->key = key; return temp; } // Driver program to test above functions int main() { /* 1 / \ 2 3 / \ / \ 4 5 6 7 */ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); createThreaded(root); cout << "Inorder traversal of created threaded tree " "is\n"; inOrder(root); return 0; }
linear
linear
/* C++ program to convert a Binary Tree to Threaded Tree */ #include <bits/stdc++.h> using namespace std; /* Structure of a node in threaded binary tree */ struct Node { int key; Node *left, *right; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. bool isThreaded; }; // Converts tree with given root to threaded // binary tree. // This function returns rightmost child of // root. Node *createThreaded(Node *root) { // Base cases : Tree is empty or has single // node if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) return root; // Find predecessor if it exists if (root->left != NULL) { // Find predecessor of root (Rightmost // child in left subtree) Node* l = createThreaded(root->left); // Link a thread from predecessor to // root. l->right = root; l->isThreaded = true; } // If current node is rightmost child if (root->right == NULL) return root; // Recur for right subtree. return createThreaded(root->right); } // A utility function to find leftmost node // in a binary tree rooted with 'root'. // This function is used in inOrder() Node *leftMost(Node *root) { while (root != NULL && root->left != NULL) root = root->left; return root; } // Function to do inorder traversal of a threadded // binary tree void inOrder(Node *root) { if (root == NULL) return; // Find the leftmost node in Binary Tree Node *cur = leftMost(root); while (cur != NULL) { cout << cur->key << " "; // If this Node is a thread Node, then go to // inorder successor if (cur->isThreaded) cur = cur->right; else // Else go to the leftmost child in right subtree cur = leftMost(cur->right); } } // A utility function to create a new node Node *newNode(int key) { Node *temp = new Node; temp->left = temp->right = NULL; temp->key = key; return temp; } // Driver program to test above functions int main() { /* 1 / \ 2 3 / \ / \ 4 5 6 7 */ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); createThreaded(root); cout << "Inorder traversal of created " "threaded tree is\n"; inOrder(root); return 0; }
constant
linear
// C++ program to print BST in given range #include<bits/stdc++.h> using namespace std; /* A Binary Tree node */ class TNode { public: int data; TNode* left; TNode* right; }; TNode* newNode(int data); /* A function that constructs Balanced Binary Search Tree from a sorted array */ TNode* sortedArrayToBST(int arr[], int start, int end) { /* Base Case */ if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end)/2; TNode *root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root->left = sortedArrayToBST(arr, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ root->right = sortedArrayToBST(arr, mid + 1, end); return root; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ TNode* newNode(int data) { TNode* node = new TNode(); node->data = data; node->left = NULL; node->right = NULL; return node; } /* A utility function to print preorder traversal of BST */ void preOrder(TNode* node) { if (node == NULL) return; cout << node->data << " "; preOrder(node->left); preOrder(node->right); } // Driver Code int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7}; int n = sizeof(arr) / sizeof(arr[0]); /* Convert List to BST */ TNode *root = sortedArrayToBST(arr, 0, n-1); cout << "PreOrder Traversal of constructed BST \n"; preOrder(root); return 0; } // This code is contributed by rathbhupendra
logn
linear
/* CPP program to check if a tree is height-balanced or not */ #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { public: int data; Node* left; Node* right; Node(int d) { int data = d; left = right = NULL; } }; // Function to calculate the height of a tree int height(Node* node) { // base case tree is empty if (node == NULL) return 0; // If tree is not empty then // height = 1 + max of left height // and right heights return 1 + max(height(node->left), height(node->right)); } // Returns true if binary tree // with root as root is height-balanced bool isBalanced(Node* root) { // for height of left subtree int lh; // for height of right subtree int rh; // If tree is empty then return true if (root == NULL) return 1; // Get the height of left and right sub trees lh = height(root->left); rh = height(root->right); if (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right)) return 1; // If we reach here then tree is not height-balanced return 0; } // Driver code int main() { Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->left->left->left = new Node(8); if (isBalanced(root)) cout << "Tree is balanced"; else cout << "Tree is not balanced"; return 0; } // This code is contributed by rathbhupendra
linear
quadratic
// C++ Code for the above approach #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, a pointer to left child and a pointer to right child */ class Node { public: int data; Node* left; Node* right; }; // Function to return a new Node Node* newNode(int data) { Node* node = new Node(); node->data = data; node->left = NULL; node->right = NULL; return (node); } // Function to convert bst to // a doubly linked list void bstTodll(Node* root, Node*& head) { // if root is NULL if (!root) return; // Convert right subtree recursively bstTodll(root->right, head); // Update root root->right = head; // if head is not NULL if (head) { // Update left of the head head->left = root; } // Update head head = root; // Convert left subtree recursively bstTodll(root->left, head); } // Function to merge two sorted linked list Node* mergeLinkedList(Node* head1, Node* head2) { /*Create head and tail for result list*/ Node* head = NULL; Node* tail = NULL; while (head1 && head2) { if (head1->data < head2->data) { if (!head) head = head1; else { tail->right = head1; head1->left = tail; } tail = head1; head1 = head1->right; } else { if (!head) head = head2; else { tail->right = head2; head2->left = tail; } tail = head2; head2 = head2->right; } } while (head1) { tail->right = head1; head1->left = tail; tail = head1; head1 = head1->right; } while (head2) { tail->right = head2; head2->left = tail; tail = head2; head2 = head2->right; } // Return the created DLL return head; } // function to convert list to bst Node* sortedListToBST(Node*& head, int n) { // if no element is left or head is null if (n <= 0 || !head) return NULL; // Create left part from the list recursively Node* left = sortedListToBST(head, n / 2); Node* root = head; root->left = left; head = head->right; // Create left part from the list recursively root->right = sortedListToBST(head, n - (n / 2) - 1); // Return the root of BST return root; } // This function merges two balanced BSTs Node* mergeTrees(Node* root1, Node* root2, int m, int n) { // Convert BSTs into sorted Doubly Linked Lists Node* head1 = NULL; bstTodll(root1, head1); head1->left = NULL; Node* head2 = NULL; bstTodll(root2, head2); head2->left = NULL; // Merge the two sorted lists into one Node* head = mergeLinkedList(head1, head2); // Construct a tree from the merged lists return sortedListToBST(head, m + n); } void printInorder(Node* node) { // if current node is NULL if (!node) { return; } printInorder(node->left); // Print node of current data cout << node->data << " "; printInorder(node->right); } /* Driver code*/ int main() { /* Create following tree as first balanced BST 100 / \ 50 300 / \ 20 70 */ Node* root1 = newNode(100); root1->left = newNode(50); root1->right = newNode(300); root1->left->left = newNode(20); root1->left->right = newNode(70); /* Create following tree as second balanced BST 80 / \ 40 120 */ Node* root2 = newNode(80); root2->left = newNode(40); root2->right = newNode(120); // Function Call Node* mergedTree = mergeTrees(root1, root2, 5, 3); cout << "Following is Inorder traversal of the merged " "tree \n"; printInorder(mergedTree); return 0; } // This code is contributed by Tapesh(tapeshdua420)
constant
linear
// Two nodes in the BST's swapped, correct the BST. #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct node { int data; struct node *left, *right; }; // A utility function to swap two integers void swap( int* a, int* b ) { int t = *a; *a = *b; *b = t; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct node* newNode(int data) { struct node* node = (struct node *)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node); } // This function does inorder traversal to find out the two swapped nodes. // It sets three pointers, first, middle and last. If the swapped nodes are // adjacent to each other, then first and middle contain the resultant nodes // Else, first and last contain the resultant nodes void correctBSTUtil( struct node* root, struct node** first, struct node** middle, struct node** last, struct node** prev ) { if( root ) { // Recur for the left subtree correctBSTUtil( root->left, first, middle, last, prev ); // If this node is smaller than the previous node, it's violating // the BST rule. if (*prev && root->data < (*prev)->data) { // If this is first violation, mark these two nodes as // 'first' and 'middle' if ( !*first ) { *first = *prev; *middle = root; } // If this is second violation, mark this node as last else *last = root; } // Mark this node as previous *prev = root; // Recur for the right subtree correctBSTUtil( root->right, first, middle, last, prev ); } } // A function to fix a given BST where two nodes are swapped. This // function uses correctBSTUtil() to find out two nodes and swaps the // nodes to fix the BST void correctBST( struct node* root ) { // Initialize pointers needed for correctBSTUtil() struct node *first, *middle, *last, *prev; first = middle = last = prev = NULL; // Set the pointers to find out two nodes correctBSTUtil( root, &first, &middle, &last, &prev ); // Fix (or correct) the tree if( first && last ) swap( &(first->data), &(last->data) ); else if( first && middle ) // Adjacent nodes swapped swap( &(first->data), &(middle->data) ); // else nodes have not been swapped, passed tree is really BST. } /* A utility function to print Inorder traversal */ void printInorder(struct node* node) { if (node == NULL) return; printInorder(node->left); cout <<" "<< node->data; printInorder(node->right); } /* Driver program to test above functions*/ int main() { /* 6 / \ 10 2 / \ / \ 1 3 7 12 10 and 2 are swapped */ struct node *root = newNode(6); root->left = newNode(10); root->right = newNode(2); root->left->left = newNode(1); root->left->right = newNode(3); root->right->right = newNode(12); root->right->left = newNode(7); cout <<"Inorder Traversal of the original tree \n"; printInorder(root); correctBST(root); cout <<"\nInorder Traversal of the fixed tree \n"; printInorder(root); return 0; } // This code is contributed by shivanisinghss2110
linear
linear
// C++ Program to find ceil of a given value in BST #include <bits/stdc++.h> using namespace std; /* A binary tree node has key, left child and right child */ class node { public: int key; node* left; node* right; }; /* Helper function that allocates a new node with the given key and NULL left and right pointers.*/ node* newNode(int key) { node* Node = new node(); Node->key = key; Node->left = NULL; Node->right = NULL; return (Node); } // Function to find ceil of a given input in BST. If input // is more than the max key in BST, return -1 int Ceil(node* root, int input) { // Base case if (root == NULL) return -1; // We found equal key if (root->key == input) return root->key; // If root's key is smaller, ceil must be in right // subtree if (root->key < input) return Ceil(root->right, input); // Else, either left subtree or root has the ceil value int ceil = Ceil(root->left, input); return (ceil >= input) ? ceil : root->key; } // Driver code int main() { node* root = newNode(8); root->left = newNode(4); root->right = newNode(12); root->left->left = newNode(2); root->left->right = newNode(6); root->right->left = newNode(10); root->right->right = newNode(14); for (int i = 0; i < 16; i++) cout << i << " " << Ceil(root, i) << endl; return 0; } // This code is contributed by rathbhupendra
logn
logn
// C++ Program to find floor of a given value in BST #include <bits/stdc++.h> using namespace std; /* A binary tree node has key, left child and right child */ class node { public: int key; node* left; node* right; }; /* Helper function that allocates a new node with the given key and NULL left and right pointers.*/ node* newNode(int key) { node* Node = new node(); Node->key = key; Node->left = NULL; Node->right = NULL; return (Node); } // Function to find floor of a given input in BST. If input // is more than the min key in BST, return -1 int Floor(node* root, int input) { // Base case if (root == NULL) return -1; // We found equal key if (root->key == input) return root->key; // If root's key is larger, floor must be in left // subtree if (root->key > input) return Floor(root->left, input); // Else, either right subtree or root has the floor // value else { int floor = Floor(root->right, input); // exception for -1 because it is being returned in // base case return (floor <= input && floor != -1) ? floor : root->key; } } // Driver code int main() { node* root = newNode(8); root->left = newNode(4); root->right = newNode(12); root->left->left = newNode(2); root->left->right = newNode(6); root->right->left = newNode(10); root->right->right = newNode(14); for (int i = 0; i < 16; i++) cout << i << " " << Floor(root, i) << endl; return 0; } // This code is contributed by rathbhupendra
logn
logn
// C++ program to find floor and ceil of a given key in BST #include <bits/stdc++.h> using namespace std; /* A binary tree node has key, left child and right child */ struct Node { int data; Node *left, *right; Node(int value) { data = value; left = right = NULL; } }; // Helper function to find floor and ceil of a given key in // BST void floorCeilBSTHelper(Node* root, int key, int& floor, int& ceil) { while (root) { if (root->data == key) { ceil = root->data; floor = root->data; return; } if (key > root->data) { floor = root->data; root = root->right; } else { ceil = root->data; root = root->left; } } return; } // Display the floor and ceil of a given key in BST. // If key is less than the min key in BST, floor will be -1; // If key is more than the max key in BST, ceil will be -1; void floorCeilBST(Node* root, int key) { // Variables 'floor' and 'ceil' are passed by reference int floor = -1, ceil = -1; floorCeilBSTHelper(root, key, floor, ceil); cout << key << ' ' << floor << ' ' << ceil << '\n'; } // Driver code int main() { Node* root = new Node(8); root->left = new Node(4); root->right = new Node(12); root->left->left = new Node(2); root->left->right = new Node(6); root->right->left = new Node(10); root->right->right = new Node(14); for (int i = 0; i < 16; i++) floorCeilBST(root, i); return 0; }
constant
logn
// C++ program of iterative traversal based method to // find common elements in two BSTs. #include <iostream> #include <stack> using namespace std; // A BST node struct Node { int key; struct Node *left, *right; }; // A utility function to create a new node Node* newNode(int ele) { Node* temp = new Node; temp->key = ele; temp->left = temp->right = NULL; return temp; } // Function two print common elements in given two trees void printCommon(Node* root1, Node* root2) { // Create two stacks for two inorder traversals stack<Node*> stack1, s1, s2; while (1) { // Push the Nodes of first tree in stack s1 if (root1) { s1.push(root1); root1 = root1->left; } // Push the Nodes of second tree in stack s2 else if (root2) { s2.push(root2); root2 = root2->left; } // Both root1 and root2 are NULL here else if (!s1.empty() && !s2.empty()) { root1 = s1.top(); root2 = s2.top(); // If current keys in two trees are same if (root1->key == root2->key) { cout << root1->key << " "; s1.pop(); s2.pop(); // Move to the inorder successor root1 = root1->right; root2 = root2->right; } else if (root1->key < root2->key) { // If Node of first tree is smaller, than // that of second tree, then its obvious // that the inorder successors of current // node can have same value as that of the // second tree Node. Thus, we pop from s2 s1.pop(); root1 = root1->right; // root2 is set to NULL, because we need // new Nodes of tree 1 root2 = NULL; } else if (root1->key > root2->key) { s2.pop(); root2 = root2->right; root1 = NULL; } } // Both roots and both stacks are empty else break; } } // A utility function to do inorder traversal void inorder(struct Node* root) { if (root) { inorder(root->left); cout << root->key << " "; inorder(root->right); } } // A utility function to insert a new Node // with given key in BST struct Node* insert(struct Node* node, int key) { // If the tree is empty, return a new Node if (node == NULL) return newNode(key); // Otherwise, recur down the tree if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); // Return the (unchanged) Node pointer return node; } // Driver program int main() { // Create first tree as shown in example Node* root1 = NULL; root1 = insert(root1, 5); root1 = insert(root1, 1); root1 = insert(root1, 10); root1 = insert(root1, 0); root1 = insert(root1, 4); root1 = insert(root1, 7); root1 = insert(root1, 9); // Create second tree as shown in example Node* root2 = NULL; root2 = insert(root2, 10); root2 = insert(root2, 7); root2 = insert(root2, 20); root2 = insert(root2, 4); root2 = insert(root2, 9); cout << "Tree 1 : " << endl; inorder(root1); cout << endl; cout << "Tree 2 : " << endl; inorder(root2); cout << "\nCommon Nodes: " << endl; printCommon(root1, root2); return 0; }
logn
linear
// An AVL Tree based C++ program to count // inversion in an array #include<bits/stdc++.h> using namespace std; // An AVL tree node struct Node { int key, height; struct Node *left, *right; // size of the tree rooted with this Node int size; }; // A utility function to get the height of // the tree rooted with N int height(struct Node *N) { if (N == NULL) return 0; return N->height; } // A utility function to size of the // tree of rooted with N int size(struct Node *N) { if (N == NULL) return 0; return N->size; } /* Helper function that allocates a new Node with the given key and NULL left and right pointers. */ struct Node* newNode(int key) { struct Node* node = new Node; node->key = key; node->left = node->right = NULL; node->height = node->size = 1; return(node); } // A utility function to right rotate // subtree rooted with y struct Node *rightRotate(struct Node *y) { struct Node *x = y->left; struct Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right))+1; x->height = max(height(x->left), height(x->right))+1; // Update sizes y->size = size(y->left) + size(y->right) + 1; x->size = size(x->left) + size(x->right) + 1; // Return new root return x; } // A utility function to left rotate // subtree rooted with x struct Node *leftRotate(struct Node *x) { struct Node *y = x->right; struct Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right))+1; y->height = max(height(y->left), height(y->right))+1; // Update sizes x->size = size(x->left) + size(x->right) + 1; y->size = size(y->left) + size(y->right) + 1; // Return new root return y; } // Get Balance factor of Node N int getBalance(struct Node *N) { if (N == NULL) return 0; return height(N->left) - height(N->right); } // Inserts a new key to the tree rotted with Node. Also, updates // *result (inversion count) struct Node* insert(struct Node* node, int key, int *result) { /* 1. Perform the normal BST rotation */ if (node == NULL) return(newNode(key)); if (key < node->key) { node->left = insert(node->left, key, result); // UPDATE COUNT OF GREATE ELEMENTS FOR KEY *result = *result + size(node->right) + 1; } else node->right = insert(node->right, key, result); /* 2. Update height and size of this ancestor node */ node->height = max(height(node->left), height(node->right)) + 1; node->size = size(node->left) + size(node->right) + 1; /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there are // 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // The following function returns inversion count in arr[] int getInvCount(int arr[], int n) { struct Node *root = NULL; // Create empty AVL Tree int result = 0; // Initialize result // Starting from first element, insert all elements one by // one in an AVL tree. for (int i=0; i<n; i++) // Note that address of result is passed as insert // operation updates result by adding count of elements // greater than arr[i] on left of arr[i] root = insert(root, arr[i], &result); return result; } // Driver program to test above int main() { int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(int); cout << "Number of inversions count are : " << getInvCount(arr,n); return 0; }
linear
nlogn
// C++ program to print leaf node from // preorder of binary search tree. #include<bits/stdc++.h> using namespace std; // Binary Search int binarySearch(int inorder[], int l, int r, int d) { int mid = (l + r)>>1; if (inorder[mid] == d) return mid; else if (inorder[mid] > d) return binarySearch(inorder, l, mid - 1, d); else return binarySearch(inorder, mid + 1, r, d); } // Function to print Leaf Nodes by doing preorder // traversal of tree using preorder and inorder arrays. void leafNodesRec(int preorder[], int inorder[], int l, int r, int *ind, int n) { // If l == r, therefore no right or left subtree. // So, it must be leaf Node, print it. if(l == r) { printf("%d ", inorder[l]); *ind = *ind + 1; return; } // If array is out of bound, return. if (l < 0 || l > r || r >= n) return; // Finding the index of preorder element // in inorder array using binary search. int loc = binarySearch(inorder, l, r, preorder[*ind]); // Incrementing the index. *ind = *ind + 1; // Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, ind, n); // Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, ind, n); } // Finds leaf nodes from given preorder traversal. void leafNodes(int preorder[], int n) { int inorder[n]; // To store inorder traversal // Copy the preorder into another array. for (int i = 0; i < n; i++) inorder[i] = preorder[i]; // Finding the inorder by sorting the array. sort(inorder, inorder + n); // Point to the index in preorder. int ind = 0; // Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, &ind, n); } // Driven Program int main() { int preorder[] = { 890, 325, 290, 530, 965 }; int n = sizeof(preorder)/sizeof(preorder[0]); leafNodes(preorder, n); return 0; }
linear
nlogn
// CPP program to find number of pairs and minimal // possible value #include <bits/stdc++.h> using namespace std; // function for finding pairs and min value void pairs(int arr[], int n, int k) { // initialize smallest and count int smallest = INT_MAX; int count = 0; // iterate over all pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { // is abs value is smaller than smallest // update smallest and reset count to 1 if (abs(arr[i] + arr[j] - k) < smallest) { smallest = abs(arr[i] + arr[j] - k); count = 1; } // if abs value is equal to smallest // increment count value else if (abs(arr[i] + arr[j] - k) == smallest) count++; } // print result cout << "Minimal Value = " << smallest << "\n"; cout << "Total Pairs = " << count << "\n"; } // driver program int main() { int arr[] = { 3, 5, 7, 5, 1, 9, 9 }; int k = 12; int n = sizeof(arr) / sizeof(arr[0]); pairs(arr, n, k); return 0; }
constant
quadratic
// C++ program to find number of pairs // and minimal possible value #include <bits/stdc++.h> using namespace std; // function for finding pairs and min value void pairs(int arr[], int n, int k) { // initialize smallest and count int smallest = INT_MAX, count = 0; set<int> s; // iterate over all pairs s.insert(arr[0]); for (int i = 1; i < n; i++) { // Find the closest elements to k - arr[i] int lower = *lower_bound(s.begin(), s.end(), k - arr[i]); int upper = *upper_bound(s.begin(), s.end(), k - arr[i]); // Find absolute value of the pairs formed // with closest greater and smaller elements. int curr_min = min(abs(lower + arr[i] - k), abs(upper + arr[i] - k)); // is abs value is smaller than smallest // update smallest and reset count to 1 if (curr_min < smallest) { smallest = curr_min; count = 1; } // if abs value is equal to smallest // increment count value else if (curr_min == smallest) count++; s.insert(arr[i]); } // print result cout << "Minimal Value = " << smallest << "\n"; cout << "Total Pairs = " << count << "\n"; } // driver program int main() { int arr[] = { 3, 5, 7, 5, 1, 9, 9 }; int k = 12; int n = sizeof(arr) / sizeof(arr[0]); pairs(arr, n, k); return 0; }
linear
nlogn
// CPP program to find rank of an // element in a stream. #include <bits/stdc++.h> using namespace std; struct Node { int data; Node *left, *right; int leftSize; }; Node* newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; temp->leftSize = 0; return temp; } // Inserting a new Node. Node* insert(Node*& root, int data) { if (!root) return newNode(data); // Updating size of left subtree. if (data <= root->data) { root->left = insert(root->left, data); root->leftSize++; } else root->right = insert(root->right, data); return root; } // Function to get Rank of a Node x. int getRank(Node* root, int x) { // Step 1. if (root->data == x) return root->leftSize; // Step 2. if (x < root->data) { if (!root->left) return -1; else return getRank(root->left, x); } // Step 3. else { if (!root->right) return -1; else { int rightSize = getRank(root->right, x); if(rightSize == -1 ) return -1; return root->leftSize + 1 + rightSize; } } } // Driver code int main() { int arr[] = { 5, 1, 4, 4, 5, 9, 7, 13, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 4; Node* root = NULL; for (int i = 0; i < n; i++) root = insert(root, arr[i]); cout << "Rank of " << x << " in stream is: " << getRank(root, x) << endl; x = 13; cout << "Rank of " << x << " in stream is: " << getRank(root, x) << endl; x = 8; cout << "Rank of " << x << " in stream is: " << getRank(root, x) << endl; return 0; }
linear
linear
// C++ program to find rank of an // element in a stream. #include <bits/stdc++.h> using namespace std; // Driver code int main() { int a[] = {5, 1, 14, 4, 15, 9, 7, 20, 11}; int key = 20; int arraySize = sizeof(a)/sizeof(a[0]); int count = 0; for(int i = 0; i < arraySize; i++) { if(a[i] <= key) { count += 1; } } cout << "Rank of " << key << " in stream is: " << count-1 << endl; return 0; } // This code is contributed by // Ashwin Loganathan.
constant
linear
// C++ program to insert element in Binary Tree #include <iostream> #include <queue> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node* left; Node* right; }; // Function to create a new node Node* CreateNode(int data) { Node* newNode = new Node(); if (!newNode) { cout << "Memory error\n"; return NULL; } newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } // Function to insert element in binary tree Node* InsertNode(Node* root, int data) { // If the tree is empty, assign new node address to root if (root == NULL) { root = CreateNode(data); return root; } // Else, do level order traversal until we find an empty // place, i.e. either left child or right child of some // node is pointing to NULL. queue<Node*> q; q.push(root); while (!q.empty()) { Node* temp = q.front(); q.pop(); if (temp->left != NULL) q.push(temp->left); else { temp->left = CreateNode(data); return root; } if (temp->right != NULL) q.push(temp->right); else { temp->right = CreateNode(data); return root; } } } /* Inorder traversal of a binary tree */ void inorder(Node* temp) { if (temp == NULL) return; inorder(temp->left); cout << temp->data << ' '; inorder(temp->right); } // Driver code int main() { Node* root = CreateNode(10); root->left = CreateNode(11); root->left->left = CreateNode(7); root->right = CreateNode(9); root->right->left = CreateNode(15); root->right->right = CreateNode(8); cout << "Inorder traversal before insertion: "; inorder(root); cout << endl; int key = 12; root = InsertNode(root, key); cout << "Inorder traversal after insertion: "; inorder(root); cout << endl; return 0; }
logn
linear
// C++ program to delete element in binary tree #include <bits/stdc++.h> using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */ struct Node { int key; struct Node *left, *right; }; /* function to create a new node of tree and return pointer */ struct Node* newNode(int key) { struct Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp; }; /* Inorder traversal of a binary tree*/ void inorder(struct Node* temp) { if (!temp) return; inorder(temp->left); cout << temp->key << " "; inorder(temp->right); } /* function to delete the given deepest node (d_node) in binary tree */ void deletDeepest(struct Node* root, struct Node* d_node) { queue<struct Node*> q; q.push(root); // Do level order traversal until last node struct Node* temp; while (!q.empty()) { temp = q.front(); q.pop(); if (temp == d_node) { temp = NULL; delete (d_node); return; } if (temp->right) { if (temp->right == d_node) { temp->right = NULL; delete (d_node); return; } else q.push(temp->right); } if (temp->left) { if (temp->left == d_node) { temp->left = NULL; delete (d_node); return; } else q.push(temp->left); } } } /* function to delete element in binary tree */ Node* deletion(struct Node* root, int key) { if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { if (root->key == key) return NULL; else return root; } queue<struct Node*> q; q.push(root); struct Node* temp; struct Node* key_node = NULL; // Do level order traversal to find deepest // node(temp) and node to be deleted (key_node) while (!q.empty()) { temp = q.front(); q.pop(); if (temp->key == key) key_node = temp; if (temp->left) q.push(temp->left); if (temp->right) q.push(temp->right); } if (key_node != NULL) { int x = temp->key; deletDeepest(root, temp); key_node->key = x; } return root; } // Driver code int main() { struct Node* root = newNode(10); root->left = newNode(11); root->left->left = newNode(7); root->left->right = newNode(12); root->right = newNode(9); root->right->left = newNode(15); root->right->right = newNode(8); cout << "Inorder traversal before deletion : "; inorder(root); int key = 11; root = deletion(root, key); cout << endl; cout << "Inorder traversal after deletion : "; inorder(root); return 0; }
linear
linear
// C++ program to delete element in binary tree #include <bits/stdc++.h> using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */ struct Node { int data; struct Node *left, *right; }; /* function to create a new node of tree and return pointer */ struct Node* newNode(int key) { struct Node* temp = new Node; temp->data = key; temp->left = temp->right = NULL; return temp; }; /* Inorder traversal of a binary tree*/ void inorder(struct Node* temp) { if (!temp) return; inorder(temp->left); cout << temp->data << " "; inorder(temp->right); } struct Node* deletion(struct Node* root, int key) { if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { if (root->data == key) return NULL; else return root; } Node* key_node = NULL; Node* temp; Node* last; queue<Node*> q; q.push(root); // Do level order traversal to find deepest // node(temp), node to be deleted (key_node) // and parent of deepest node(last) while (!q.empty()) { temp = q.front(); q.pop(); if (temp->data == key) key_node = temp; if (temp->left) { last = temp; // storing the parent node q.push(temp->left); } if (temp->right) { last = temp; // storing the parent node q.push(temp->right); } } if (key_node != NULL) { key_node->data = temp->data; // replacing key_node's data to // deepest node's data if (last->right == temp) last->right = NULL; else last->left = NULL; delete (temp); } return root; } // Driver code int main() { struct Node* root = newNode(9); root->left = newNode(2); root->left->left = newNode(4); root->left->right = newNode(7); root->right = newNode(8); cout << "Inorder traversal before deletion : "; inorder(root); int key = 7; root = deletion(root, key); cout << endl; cout << "Inorder traversal after deletion : "; inorder(root); return 0; }
linear
linear
// C++ implementation of tree using array // numbering starting from 0 to n-1. #include<bits/stdc++.h> using namespace std; char tree[10]; int root(char key) { if (tree[0] != '\0') cout << "Tree already had root"; else tree[0] = key; return 0; } int set_left(char key, int parent) { if (tree[parent] == '\0') cout << "\nCan't set child at " << (parent * 2) + 1 << " , no parent found"; else tree[(parent * 2) + 1] = key; return 0; } int set_right(char key, int parent) { if (tree[parent] == '\0') cout << "\nCan't set child at " << (parent * 2) + 2 << " , no parent found"; else tree[(parent * 2) + 2] = key; return 0; } int print_tree() { cout << "\n"; for (int i = 0; i < 10; i++) { if (tree[i] != '\0') cout << tree[i]; else cout << "-"; } return 0; } // Driver Code int main() { root('A'); set_left('B',0); set_right('C', 0); set_left('D', 1); set_right('E', 1); set_right('F', 2); print_tree(); return 0; }
linear
logn
// C++ program to evaluate an expression tree #include <bits/stdc++.h> using namespace std; // Class to represent the nodes of syntax tree class node { public: string info; node *left = NULL, *right = NULL; node(string x) { info = x; } }; // Utility function to return the integer value // of a given string int toInt(string s) { int num = 0; // Check if the integral value is // negative or not // If it is not negative, generate the number // normally if(s[0]!='-') for (int i=0; i<s.length(); i++) num = num*10 + (int(s[i])-48); // If it is negative, calculate the +ve number // first ignoring the sign and invert the // sign at the end else { for (int i=1; i<s.length(); i++) num = num*10 + (int(s[i])-48); num = num*-1; } return num; } // This function receives a node of the syntax tree // and recursively evaluates it int eval(node* root) { // empty tree if (!root) return 0; // leaf node i.e, an integer if (!root->left && !root->right) return toInt(root->info); // Evaluate left subtree int l_val = eval(root->left); // Evaluate right subtree int r_val = eval(root->right); // Check which operator to apply if (root->info=="+") return l_val+r_val; if (root->info=="-") return l_val-r_val; if (root->info=="*") return l_val*r_val; return l_val/r_val; } //driver function to check the above program int main() { // create a syntax tree node *root = new node("+"); root->left = new node("*"); root->left->left = new node("5"); root->left->right = new node("-4"); root->right = new node("-"); root->right->left = new node("100"); root->right->right = new node("20"); cout << eval(root) << endl; delete(root); root = new node("+"); root->left = new node("*"); root->left->left = new node("5"); root->left->right = new node("4"); root->right = new node("-"); root->right->left = new node("100"); root->right->right = new node("/"); root->right->right->left = new node("20"); root->right->right->right = new node("2"); cout << eval(root); return 0; }
constant
linear
// C++ program to check if a given Binary Tree is symmetric // or not #include <bits/stdc++.h> using namespace std; // A Binary Tree Node struct Node { int key; struct Node *left, *right; }; // Utility function to create new Node Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp); } // Returns true if trees with roots as root1 and root2 are // mirror bool isMirror(struct Node* root1, struct Node* root2) { // If both trees are empty, then they are mirror images if (root1 == NULL && root2 == NULL) return true; // For two trees to be mirror images, the following // three conditions must be true // 1.) Their root node's key must be same // 2.) left subtree of left tree and right subtree of // right tree have to be mirror images // 3.) right subtree of left tree and left subtree of // right tree have to be mirror images if (root1 && root2 && root1->key == root2->key) return isMirror(root1->left, root2->right) && isMirror(root1->right, root2->left); // if none of above conditions is true then root1 // and root2 are not mirror images return false; } // Returns true if a tree is symmetric i.e. mirror image of itself bool isSymmetric(struct Node* root) { // Check if tree is mirror of itself return isMirror(root, root); } // Driver code int main() { // Let us construct the Tree shown in the above figure Node* root = newNode(1); root->left = newNode(2); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(4); root->right->left = newNode(4); root->right->right = newNode(3); if (isSymmetric(root)) cout << "Symmetric"; else cout << "Not symmetric"; return 0; } // This code is contributed by Sania Kumari Gupta
logn
linear
// C++ program to print inorder traversal // using stack. #include<bits/stdc++.h> using namespace std; /* A binary tree Node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; Node (int data) { this->data = data; left = right = NULL; } }; /* Iterative function for inorder tree traversal */ void inOrder(struct Node *root) { stack<Node *> s; Node *curr = root; while (curr != NULL || s.empty() == false) { /* Reach the left most Node of the curr Node */ while (curr != NULL) { /* place pointer to a tree node on the stack before traversing the node's left subtree */ s.push(curr); curr = curr->left; } /* Current must be NULL at this point */ curr = s.top(); s.pop(); cout << curr->data << " "; /* we have visited the node and its left subtree. Now, it's right subtree's turn */ curr = curr->right; } /* end of while */ } /* Driver program to test above functions*/ int main() { /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ struct Node *root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); inOrder(root); return 0; }
linear
linear
// C++ program for finding postorder // traversal of BST from preorder traversal #include <bits/stdc++.h> using namespace std; // Function to find postorder traversal from // preorder traversal. void findPostOrderUtil(int pre[], int n, int minval, int maxval, int& preIndex) { // If entire preorder array is traversed then // return as no more element is left to be // added to post order array. if (preIndex == n) return; // If array element does not lie in range specified, // then it is not part of current subtree. if (pre[preIndex] < minval || pre[preIndex] > maxval) { return; } // Store current value, to be printed later, after // printing left and right subtrees. Increment // preIndex to find left and right subtrees, // and pass this updated value to recursive calls. int val = pre[preIndex]; preIndex++; // All elements with value between minval and val // lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex); // All elements with value between val and maxval // lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex); cout << val << " "; } // Function to find postorder traversal. void findPostOrder(int pre[], int n) { // To store index of element to be // traversed next in preorder array. // This is passed by reference to // utility function. int preIndex = 0; findPostOrderUtil(pre, n, INT_MIN, INT_MAX, preIndex); } // Driver code int main() { int pre[] = { 40, 30, 35, 80, 100 }; int n = sizeof(pre) / sizeof(pre[0]); // Calling function findPostOrder(pre, n); return 0; }
linear
linear
// C++ implementation to replace each node // in binary tree with the sum of its inorder // predecessor and successor #include <bits/stdc++.h> using namespace std; // node of a binary tree struct Node { int data; struct Node* left, *right; }; // function to get a new node of a binary tree struct Node* getNode(int data) { // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data; new_node->data = data; new_node->left = new_node->right = NULL; return new_node; } // function to store the inorder traversal // of the binary tree in 'arr' void storeInorderTraversal(struct Node* root, vector<int>& arr) { // if root is NULL if (!root) return; // first recur on left child storeInorderTraversal(root->left, arr); // then store the root's data in 'arr' arr.push_back(root->data); // now recur on right child storeInorderTraversal(root->right, arr); } // function to replace each node with the sum of its // inorder predecessor and successor void replaceNodeWithSum(struct Node* root, vector<int> arr, int* i) { // if root is NULL if (!root) return; // first recur on left child replaceNodeWithSum(root->left, arr, i); // replace node's data with the sum of its // inorder predecessor and successor root->data = arr[*i - 1] + arr[*i + 1]; // move 'i' to point to the next 'arr' element ++*i; // now recur on right child replaceNodeWithSum(root->right, arr, i); } // Utility function to replace each node in binary // tree with the sum of its inorder predecessor // and successor void replaceNodeWithSumUtil(struct Node* root) { // if tree is empty if (!root) return; vector<int> arr; // store the value of inorder predecessor // for the leftmost leaf arr.push_back(0); // store the inorder traversal of the tree in 'arr' storeInorderTraversal(root, arr); // store the value of inorder successor // for the rightmost leaf arr.push_back(0); // replace each node with the required sum int i = 1; replaceNodeWithSum(root, arr, &i); } // function to print the preorder traversal // of a binary tree void preorderTraversal(struct Node* root) { // if root is NULL if (!root) return; // first print the data of node cout << root->data << " "; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right); } // Driver program to test above int main() { // binary tree formation struct Node* root = getNode(1); /* 1 */ root->left = getNode(2); /* / \ */ root->right = getNode(3); /* 2 3 */ root->left->left = getNode(4); /* / \ / \ */ root->left->right = getNode(5); /* 4 5 6 7 */ root->right->left = getNode(6); root->right->right = getNode(7); cout << "Preorder Traversal before tree modification:n"; preorderTraversal(root); replaceNodeWithSumUtil(root); cout << "\nPreorder Traversal after tree modification:n"; preorderTraversal(root); return 0; }
linear
linear
// C++ implementation to replace each node // in binary tree with the sum of its inorder // predecessor and successor #include <bits/stdc++.h> using namespace std; // node of a binary tree struct Node { int data; struct Node* left, *right; }; // function to get a new node of a binary tree struct Node* getNode(int data) { // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data; new_node->data = data; new_node->left = new_node->right = NULL; return new_node; } // function to print the preorder traversal // of a binary tree void preorderTraversal(struct Node* root) { // if root is NULL if (!root) return; // first print the data of node cout << root->data << " "; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right); } void inOrderTraverse(struct Node* root, struct Node* &prev, int &prevVal) { if(root == NULL) return; inOrderTraverse(root->left, prev, prevVal); if(prev == NULL) { prev = root; prevVal = 0; } else { int temp = prev->data; prev->data = prevVal + root->data; prev = root; prevVal = temp; } inOrderTraverse(root->right, prev, prevVal); } // Driver program to test above int main() { // binary tree formation struct Node* root = getNode(1); /* 1 */ root->left = getNode(2); /* / \ */ root->right = getNode(3); /* 2 3 */ root->left->left = getNode(4); /* / \ / \ */ root->left->right = getNode(5); /* 4 5 6 7 */ root->right->left = getNode(6); root->right->right = getNode(7); cout << "Preorder Traversal before tree modification:\n"; preorderTraversal(root); struct Node* prev = NULL; int prevVal = -1; inOrderTraverse(root, prev, prevVal); // update righmost node. prev->data = prevVal; cout << "\nPreorder Traversal after tree modification:\n"; preorderTraversal(root); return 0; }
linear
linear
// Recursive CPP program for level // order traversal of Binary Tree #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: int data; node *left, *right; }; /* Function prototypes */ void printCurrentLevel(node* root, int level); int height(node* node); node* newNode(int data); /* Function to print level order traversal a tree*/ void printLevelOrder(node* root) { int h = height(root); int i; for (i = 1; i <= h; i++) printCurrentLevel(root, i); } /* Print nodes at a current level */ void printCurrentLevel(node* root, int level) { if (root == NULL) return; if (level == 1) cout << root->data << " "; else if (level > 1) { printCurrentLevel(root->left, level - 1); printCurrentLevel(root->right, level - 1); } } /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(node* node) { if (node == NULL) return 0; else { /* compute the height of each subtree */ int lheight = height(node->left); int rheight = height(node->right); /* use the larger one */ if (lheight > rheight) { return (lheight + 1); } else { return (rheight + 1); } } } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ node* newNode(int data) { node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node); } /* Driver code*/ int main() { node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << "Level Order traversal of binary tree is \n"; printLevelOrder(root); return 0; } // This code is contributed by rathbhupendra
linear
quadratic
/* C++ program to print level order traversal using STL */ #include <bits/stdc++.h> using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; // Iterative method to find height of Binary Tree void printLevelOrder(Node* root) { // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue<Node*> q; // Enqueue Root and initialize height q.push(root); while (q.empty() == false) { // Print front of queue and remove it from queue Node* node = q.front(); cout << node->data << " "; q.pop(); /* Enqueue left child */ if (node->left != NULL) q.push(node->left); /*Enqueue right child */ if (node->right != NULL) q.push(node->right); } } // Utility function to create a new tree node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver program to test above functions int main() { // Let us create binary tree shown in above diagram Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << "Level Order traversal of binary tree is \n"; printLevelOrder(root); return 0; }
linear
linear
// C++ program for recursive level // order traversal in spiral form #include <bits/stdc++.h> using namespace std; // A binary tree node has data, // pointer to left child and a // pointer to right child struct node { int data; struct node* left; struct node* right; }; // Function prototypes void printGivenLevel(struct node* root, int level, int ltr); int height(struct node* node); struct node* newNode(int data); // Function to print spiral traversal of a tree void printSpiral(struct node* root) { int h = height(root); int i; // ltr -> Left to Right. If this variable // is set,then the given level is traversed // from left to right. bool ltr = false; for (i = 1; i <= h; i++) { printGivenLevel(root, i, ltr); // Revert ltr to traverse next // level in opposite order ltr = !ltr; } } // Print nodes at a given level void printGivenLevel(struct node* root, int level, int ltr) { if (root == NULL) return; if (level == 1) cout << root->data << " "; else if (level > 1) { if (ltr) { printGivenLevel(root->left, level - 1, ltr); printGivenLevel(root->right, level - 1, ltr); } else { printGivenLevel(root->right, level - 1, ltr); printGivenLevel(root->left, level - 1, ltr); } } } // Compute the "height" of a tree -- the number of // nodes along the longest path from the root node // down to the farthest leaf node. int height(struct node* node) { if (node == NULL) return 0; else { // Compute the height of each subtree int lheight = height(node->left); int rheight = height(node->right); // Use the larger one if (lheight > rheight) return (lheight + 1); else return (rheight + 1); } } // Helper function that allocates a new // node with the given data and NULL left // and right pointers. struct node* newNode(int data) { node* newnode = new node(); newnode->data = data; newnode->left = NULL; newnode->right = NULL; return (newnode); } // Driver code int main() { struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); printf("Spiral Order traversal of " "binary tree is \n"); printSpiral(root); return 0; } // This code is contributed by samrat2825
linear
quadratic
// C++ implementation of a O(n) time method for spiral order // traversal #include <iostream> #include <stack> using namespace std; // Binary Tree node struct node { int data; struct node *left, *right; }; void printSpiral(struct node* root) { if (root == NULL) return; // NULL check // Create two stacks to store alternate levels stack<struct node*> s1; // For levels to be printed from right to left stack<struct node*> s2; // For levels to be printed from left to right // Push first level to first stack 's1' s1.push(root); // Keep printing while any of the stacks has some nodes while (!s1.empty() || !s2.empty()) { // Print nodes of current level from s1 and push // nodes of next level to s2 while (!s1.empty()) { struct node* temp = s1.top(); s1.pop(); cout << temp->data << " "; // Note that is right is pushed before left if (temp->right) s2.push(temp->right); if (temp->left) s2.push(temp->left); } // Print nodes of current level from s2 and push // nodes of next level to s1 while (!s2.empty()) { struct node* temp = s2.top(); s2.pop(); cout << temp->data << " "; // Note that is left is pushed before right if (temp->left) s1.push(temp->left); if (temp->right) s1.push(temp->right); } } } // A utility function to create a new node struct node* newNode(int data) { struct node* node = new struct node; node->data = data; node->left = NULL; node->right = NULL; return (node); } int main() { struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << "Spiral Order traversal of binary tree is \n"; printSpiral(root); return 0; }
linear
linear
// C++ implementation of above approach #include <iostream> #include <stack> using namespace std; // Binary Tree node struct Node { int key; struct Node *left, *right; }; void spiralPrint(struct Node* root) { // Declare a deque deque<Node*> dq; // Insert the root of the tree into the deque dq.push_back(root); // Create a variable that will switch in each iteration bool reverse = true; // Start iteration while (!dq.empty()) { // Save the size of the deque here itself, as in // further steps the size of deque will frequently // change int n = dq.size(); // If we are printing left to right if (!reverse) { // Iterate from left to right while (n--) { // Insert the child from the back of the // deque Left child first if (dq.front()->left != NULL) dq.push_back(dq.front()->left); if (dq.front()->right != NULL) dq.push_back(dq.front()->right); // Print the current processed element cout << dq.front()->key << " "; dq.pop_front(); } // Switch reverse for next traversal reverse = !reverse; } else { // If we are printing right to left // Iterate the deque in reverse order and insert // the children from the front while (n--) { // Insert the child in the front of the // deque Right child first if (dq.back()->right != NULL) dq.push_front(dq.back()->right); if (dq.back()->left != NULL) dq.push_front(dq.back()->left); // Print the current processed element cout << dq.back()->key << " "; dq.pop_back(); } // Switch reverse for next traversal reverse = !reverse; } } } // A utility function to create a new node struct Node* newNode(int data) { struct Node* node = new struct Node; node->key = data; node->left = NULL; node->right = NULL; return (node); } int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << "Spiral Order traversal of binary tree is :\n"; spiralPrint(root); return 0; } // This code is contributed by Abhijeet Kumar(abhijeet19403)
linear
linear
/* C++ program for special order traversal */ #include <iostream> #include <queue> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left; Node *right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ Node *newNode(int data) { Node *node = new Node; node->data = data; node->right = node->left = NULL; return node; } /* Given a perfect binary tree, print its nodes in specific level order */ void printSpecificLevelOrder(Node *root) { if (root == NULL) return; // Let us print root and next level first cout << root->data; // / Since it is perfect Binary Tree, right is not checked if (root->left != NULL) cout << " " << root->left->data << " " << root->right->data; // Do anything more if there are nodes at next level in // given perfect Binary Tree if (root->left->left == NULL) return; // Create a queue and enqueue left and right children of root queue <Node *> q; q.push(root->left); q.push(root->right); // We process two nodes at a time, so we need two variables // to store two front items of queue Node *first = NULL, *second = NULL; // traversal loop while (!q.empty()) { // Pop two items from queue first = q.front(); q.pop(); second = q.front(); q.pop(); // Print children of first and second in reverse order cout << " " << first->left->data << " " << second->right->data; cout << " " << first->right->data << " " << second->left->data; // If first and second have grandchildren, enqueue them // in reverse order if (first->left->left != NULL) { q.push(first->left); q.push(second->right); q.push(first->right); q.push(second->left); } } } /* Driver program to test above functions*/ int main() { //Perfect Binary Tree of Height 4 Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); root->right->left->left = newNode(12); root->right->left->right = newNode(13); root->right->right->left = newNode(14); root->right->right->right = newNode(15); root->left->left->left->left = newNode(16); root->left->left->left->right = newNode(17); root->left->left->right->left = newNode(18); root->left->left->right->right = newNode(19); root->left->right->left->left = newNode(20); root->left->right->left->right = newNode(21); root->left->right->right->left = newNode(22); root->left->right->right->right = newNode(23); root->right->left->left->left = newNode(24); root->right->left->left->right = newNode(25); root->right->left->right->left = newNode(26); root->right->left->right->right = newNode(27); root->right->right->left->left = newNode(28); root->right->right->left->right = newNode(29); root->right->right->right->left = newNode(30); root->right->right->right->right = newNode(31); cout << "Specific Level Order traversal of binary tree is \n"; printSpecificLevelOrder(root); return 0; }
linear
linear
// C++ program to reverse // alternate levels of a tree #include <bits/stdc++.h> using namespace std; struct Node { char key; Node *left, *right; }; void preorder(struct Node *root1, struct Node* root2, int lvl) { // Base cases if (root1 == NULL || root2==NULL) return; // Swap subtrees if level is even if (lvl%2 == 0) swap(root1->key, root2->key); // Recur for left and right // subtrees (Note : left of root1 // is passed and right of root2 in // first call and opposite // in second call. preorder(root1->left, root2->right, lvl+1); preorder(root1->right, root2->left, lvl+1); } // This function calls preorder() // for left and right children // of root void reverseAlternate(struct Node *root) { preorder(root->left, root->right, 0); } // Inorder traversal (used to print initial and // modified trees) void printInorder(struct Node *root) { if (root == NULL) return; printInorder(root->left); cout << root->key << " "; printInorder(root->right); } // A utility function to create a new node Node *newNode(int key) { Node *temp = new Node; temp->left = temp->right = NULL; temp->key = key; return temp; } // Driver program to test above functions int main() { struct Node *root = newNode('a'); root->left = newNode('b'); root->right = newNode('c'); root->left->left = newNode('d'); root->left->right = newNode('e'); root->right->left = newNode('f'); root->right->right = newNode('g'); root->left->left->left = newNode('h'); root->left->left->right = newNode('i'); root->left->right->left = newNode('j'); root->left->right->right = newNode('k'); root->right->left->left = newNode('l'); root->right->left->right = newNode('m'); root->right->right->left = newNode('n'); root->right->right->right = newNode('o'); cout << "Inorder Traversal of given tree\n"; printInorder(root); reverseAlternate(root); cout << "\n\nInorder Traversal of modified tree\n"; printInorder(root); return 0; }
logn
linear
// C++ program to implement iterative preorder traversal #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, left child and right child */ struct node { int data; struct node* left; struct node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/ struct node* newNode(int data) { struct node* node = new struct node; node->data = data; node->left = NULL; node->right = NULL; return (node); } // An iterative process to print preorder traversal of Binary tree void iterativePreorder(node* root) { // Base Case if (root == NULL) return; // Create an empty stack and push root to it stack<node*> nodeStack; nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ while (nodeStack.empty() == false) { // Pop the top item from stack and print it struct node* node = nodeStack.top(); printf("%d ", node->data); nodeStack.pop(); // Push right and left children of the popped node to stack if (node->right) nodeStack.push(node->right); if (node->left) nodeStack.push(node->left); } } // Driver program to test above functions int main() { /* Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2 */ struct node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->left = newNode(2); iterativePreorder(root); return 0; }
logn
linear
#include <bits/stdc++.h> using namespace std; // Tree Node struct Node { int data; Node *left, *right; Node(int data) { this->data = data; this->left = this->right = NULL; } }; // Iterative function to do Preorder traversal of the tree void preorderIterative(Node* root) { if (root == NULL) return; stack<Node*> st; // start from root node (set current node to root node) Node* curr = root; // run till stack is not empty or current is // not NULL while (!st.empty() || curr != NULL) { // Print left children while exist // and keep pushing right into the // stack. while (curr != NULL) { cout << curr->data << " "; if (curr->right) st.push(curr->right); curr = curr->left; } // We reach when curr is NULL, so We // take out a right child from stack if (st.empty() == false) { curr = st.top(); st.pop(); } } } // Driver Code int main() { Node* root = new Node(10); root->left = new Node(20); root->right = new Node(30); root->left->left = new Node(40); root->left->left->left = new Node(70); root->left->right = new Node(50); root->right->left = new Node(60); root->left->left->right = new Node(80); preorderIterative(root); return 0; }
logn
linear
// C++ program for diagonal // traversal of Binary Tree #include <bits/stdc++.h> using namespace std; // Tree node struct Node { int data; Node *left, *right; }; /* root - root of the binary tree d - distance of current line from rightmost -topmost slope. diagonalPrint - multimap to store Diagonal elements (Passed by Reference) */ void diagonalPrintUtil(Node* root, int d, map<int, vector<int>> &diagonalPrint) { // Base case if (!root) return; // Store all nodes of same // line together as a vector diagonalPrint[d].push_back(root->data); // Increase the vertical // distance if left child diagonalPrintUtil(root->left, d + 1, diagonalPrint); // Vertical distance remains // same for right child diagonalPrintUtil(root->right, d, diagonalPrint); } // Print diagonal traversal // of given binary tree void diagonalPrint(Node* root) { // create a map of vectors // to store Diagonal elements map<int, vector<int> > diagonalPrint; diagonalPrintUtil(root, 0, diagonalPrint); cout << "Diagonal Traversal of binary tree : \n"; for (auto it :diagonalPrint) { vector<int> v=it.second; for(auto it:v) cout<<it<<" "; cout<<endl; } } // Utility method to create a new node Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } // Driver program int main() { Node* root = newNode(8); root->left = newNode(3); root->right = newNode(10); root->left->left = newNode(1); root->left->right = newNode(6); root->right->right = newNode(14); root->right->right->left = newNode(13); root->left->right->left = newNode(4); root->left->right->right = newNode(7); /* Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(9); root->left->right = newNode(6); root->right->left = newNode(4); root->right->right = newNode(5); root->right->left->right = newNode(7); root->right->left->left = newNode(12); root->left->right->left = newNode(11); root->left->left->right = newNode(10);*/ diagonalPrint(root); return 0; }
linear
nlogn
#include <bits/stdc++.h> using namespace std; // Tree node struct Node { int data; Node *left, *right; }; vector<int> diagonal(Node* root) { vector<int> diagonalVals; if (!root) return diagonalVals; // The leftQueue will be a queue which will store all // left pointers while traversing the tree, and will be // utilized when at any point right pointer becomes NULL queue<Node*> leftQueue; Node* node = root; while (node) { // Add current node to output diagonalVals.push_back(node->data); // If left child available, add it to queue if (node->left) leftQueue.push(node->left); // if right child, transfer the node to right if (node->right) node = node->right; else { // If left child Queue is not empty, utilize it // to traverse further if (!leftQueue.empty()) { node = leftQueue.front(); leftQueue.pop(); } else { // All the right childs traversed and no // left child left node = NULL; } } } return diagonalVals; } // Utility method to create a new node Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } // Driver program int main() { Node* root = newNode(8); root->left = newNode(3); root->right = newNode(10); root->left->left = newNode(1); root->left->right = newNode(6); root->right->right = newNode(14); root->right->right->left = newNode(13); root->left->right->left = newNode(4); root->left->right->right = newNode(7); /* Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(9); root->left->right = newNode(6); root->right->left = newNode(4); root->right->right = newNode(5); root->right->left->right = newNode(7); root->right->left->left = newNode(12); root->left->right->left = newNode(11); root->left->left->right = newNode(10);*/ vector<int> diagonalValues = diagonal(root); for (int i = 0; i < diagonalValues.size(); i++) { cout << diagonalValues[i] << " "; } cout << endl; return 0; }
linear
nlogn
#include <bits/stdc++.h> using namespace std; struct Node { int data; Node *left, *right; }; Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } vector <vector <int>> result; void diagonalPrint(Node* root) { if(root == NULL) return; queue <Node*> q; q.push(root); while(!q.empty()) { int size = q.size(); vector <int> answer; while(size--) { Node* temp = q.front(); q.pop(); // traversing each component; while(temp) { answer.push_back(temp->data); if(temp->left) q.push(temp->left); temp = temp->right; } } result.push_back(answer); } } int main() { Node* root = newNode(8); root->left = newNode(3); root->right = newNode(10); root->left->left = newNode(1); root->left->right = newNode(6); root->right->right = newNode(14); root->right->right->left = newNode(13); root->left->right->left = newNode(4); root->left->right->right = newNode(7); diagonalPrint(root); for(int i=0 ; i<result.size() ; i++) { for(int j=0 ; j<result[i].size() ; j++) cout<<result[i][j]<<" "; cout<<endl; } return 0; }
linear
linear
/* C++ program to print the diagonal traversal of binary * tree*/ #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } // root node Node* root; // function to print in diagonal order void traverse() { // if the tree is empty, do not have to print // anything if (root == NULL) return; // if root is not empty, point curr node to the // root node Node* curr = root; // Maintain a queue to store left child queue<Node*> q; // continue till the queue is empty and curr is null while (!q.empty() || curr != NULL) { // if curr is not null // 1. print the data of the curr node // 2. if left child is present, add it to the queue // 3. Move curr pointer to the right if (curr != NULL) { cout << curr->data << " "; if (curr->left != NULL) q.push(curr->left); curr = curr->right; } // if curr is null, remove a node from the queue // and point it to curr node else { curr = q.front(); q.pop(); } } } // Driver Code int main() { root = newNode(8); root->left = newNode(3); root->right = newNode(10); root->left->left = newNode(1); root->left->right = newNode(6); root->right->right = newNode(14); root->right->right->left = newNode(13); root->left->right->left = newNode(4); root->left->right->right = newNode(7); traverse(); } // This code is contributed by Abhijeet Kumar(abhijeet19403)
linear
linear
#include <iostream> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node *left, *right; }; // Utility function to create a new tree node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = nullptr; return temp; } // A simple function to print leaf nodes of a binary tree void printLeaves(Node* root) { if (root == nullptr) return; printLeaves(root->left); // Print it if it is a leaf node if (!(root->left) && !(root->right)) cout << root->data << " "; printLeaves(root->right); } // A function to print all left boundary nodes, except a // leaf node. Print the nodes in TOP DOWN manner void printBoundaryLeft(Node* root) { if (root == nullptr) return; if (root->left) { // to ensure top down order, print the node // before calling itself for left subtree cout << root->data << " "; printBoundaryLeft(root->left); } else if (root->right) { cout << root->data << " "; printBoundaryLeft(root->right); } // do nothing if it is a leaf node, this way we avoid // duplicates in output } // A function to print all right boundary nodes, except a // leaf node Print the nodes in BOTTOM UP manner void printBoundaryRight(Node* root) { if (root == nullptr) return; if (root->right) { // to ensure bottom up order, first call for right // subtree, then print this node printBoundaryRight(root->right); cout << root->data << " "; } else if (root->left) { printBoundaryRight(root->left); cout << root->data << " "; } // do nothing if it is a leaf node, this way we avoid // duplicates in output } // A function to do boundary traversal of a given binary // tree void printBoundary(Node* root) { if (root == nullptr) return; cout << root->data << " "; // Print the left boundary in top-down manner. printBoundaryLeft(root->left); // Print all leaf nodes printLeaves(root->left); printLeaves(root->right); // Print the right boundary in bottom-up manner printBoundaryRight(root->right); } // Driver program to test above functions int main() { // Let us construct the tree given in the above diagram Node* root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); printBoundary(root); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
linear
linear
#include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node *left, *right; }; // Utility function to create a new tree node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = nullptr; return temp; } bool isLeaf(Node* node){ if(node->left == NULL && node->right==NULL){ return true; } return false; } void addLeftBound(Node * root, vector<int>& ans){ //Go left left and no left then right but again check from left root = root->left; while(root!=NULL){ if(!isLeaf(root)) ans.push_back(root->data); if(root->left !=NULL) root = root->left; else root = root->right; } } void addRightBound(Node * root, vector<int>& ans){ //Go right right and no right then left but again check from right root = root->right; //As we need the reverse of this for Anticlockwise stack<int> stk; while(root!=NULL){ if(!isLeaf(root)) stk.push(root->data); if(root->right !=NULL) root = root->right; else root = root->left; } while(!stk.empty()){ ans.push_back(stk.top()); stk.pop(); } } //its kind of inorder void addLeaves(Node * root, vector<int>& ans){ if(root==NULL){ return; } if(isLeaf(root)){ ans.push_back(root->data); //just store leaf nodes return; } addLeaves(root->left,ans); addLeaves(root->right,ans); } vector <int> boundary(Node *root) { //Your code here vector<int> ans; if(root==NULL) return ans; if(!isLeaf(root)) ans.push_back(root->data); // if leaf then its done by addLeaf addLeftBound(root,ans); addLeaves(root,ans); addRightBound(root,ans); return ans; } int main() { // Let us construct the tree given in the above diagram Node* root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); vector<int>ans = boundary(root); for(int v : ans){ cout<<v<<" "; } cout<<"\n"; return 0; } //Code done by Balakrishnan R (rbkraj000)
linear
linear
//C++ program to find density of a binary tree #include<bits/stdc++.h> // A binary tree node struct Node { int data; Node *left, *right; }; // Helper function to allocates a new node Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } // Function to compute height and // size of a binary tree int heighAndSize(Node* node, int &size) { if (node==NULL) return 0; // compute height of each subtree int l = heighAndSize(node->left, size); int r = heighAndSize(node->right, size); //increase size by 1 size++; //return larger of the two return (l > r) ? l + 1 : r + 1; } //function to calculate density of a binary tree float density(Node* root) { if (root == NULL) return 0; int size = 0; // To store size // Finds height and size int _height = heighAndSize(root, size); return (float)size/_height; } // Driver code to test above methods int main() { Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); printf("Density of given binary tree is %f", density(root)); return 0; }
logn
linear
// C++ program to find height of full binary tree // using preorder #include <bits/stdc++.h> using namespace std; // function to return max of left subtree height // or right subtree height int findDepthRec(char tree[], int n, int& index) { if (index >= n || tree[index] == 'l') return 0; // calc height of left subtree (In preorder // left subtree is processed before right) index++; int left = findDepthRec(tree, n, index); // calc height of right subtree index++; int right = findDepthRec(tree, n, index); return max(left, right) + 1; } // Wrapper over findDepthRec() int findDepth(char tree[], int n) { int index = 0; return findDepthRec(tree, n, index); } // Driver program int main() { // Your C++ Code char tree[] = "nlnnlll"; int n = strlen(tree); cout << findDepth(tree, n) << endl; return 0; }
constant
linear
// C code to modify binary tree for // traversal using only right pointer #include <bits/stdc++.h> using namespace std; // A binary tree node has data, // left child and right child struct Node { int data; struct Node* left; struct Node* right; }; // function that allocates a new node // with the given data and NULL left // and right pointers. struct Node* newNode(int data) { struct Node* node = new struct Node; node->data = data; node->left = NULL; node->right = NULL; return (node); } // Function to modify tree struct Node* modifytree(struct Node* root) { struct Node* right = root->right; struct Node* rightMost = root; // if the left tree exists if (root->left) { // get the right-most of the // original left subtree rightMost = modifytree(root->left); // set root right to left subtree root->right = root->left; root->left = NULL; } // if the right subtree does // not exists we are done! if (!right) return rightMost; // set right pointer of right-most // of the original left subtree rightMost->right = right; // modify the rightsubtree rightMost = modifytree(right); return rightMost; } // printing using right pointer only void printpre(struct Node* root) { while (root != NULL) { cout << root->data << " "; root = root->right; } } // Driver program to test above functions int main() { /* Constructed binary tree is 10 / \ 8 2 / \ 3 5 */ struct Node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); modifytree(root); printpre(root); return 0; }
linear
linear
// C++ code to modify binary tree for // traversal using only right pointer #include <iostream> #include <stack> #include <stdio.h> #include <stdlib.h> using namespace std; // A binary tree node has data, // left child and right child struct Node { int data; struct Node* left; struct Node* right; }; // Helper function that allocates a new // node with the given data and NULL // left and right pointers. struct Node* newNode(int data) { struct Node* node = new struct Node; node->data = data; node->left = NULL; node->right = NULL; return (node); } // An iterative process to set the right // pointer of Binary tree void modifytree(struct Node* root) { // Base Case if (root == NULL) return; // Create an empty stack and push root to it stack<Node*> nodeStack; nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ struct Node* pre = NULL; while (nodeStack.empty() == false) { // Pop the top item from stack struct Node* node = nodeStack.top(); nodeStack.pop(); // Push right and left children of // the popped node to stack if (node->right) nodeStack.push(node->right); if (node->left) nodeStack.push(node->left); // check if some previous node exists if (pre != NULL) { // set the right pointer of // previous node to current pre->right = node; } // set previous node as current node pre = node; } } // printing using right pointer only void printpre(struct Node* root) { while (root != NULL) { cout << root->data << " "; root = root->right; } } // Driver code int main() { /* Constructed binary tree is 10 / \ 8 2 / \ 3 5 */ struct Node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); modifytree(root); printpre(root); return 0; }
linear
linear
/* C++ program to construct tree using inorder and preorder traversals */ #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: char data; node* left; node* right; }; /* Prototypes for utility functions */ int search(char arr[], int strt, int end, char value); node* newNode(char data); /* Recursive function to construct binary of size len from Inorder traversal in[] and Preorder traversal pre[]. Initial values of inStrt and inEnd should be 0 and len -1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree */ node* buildTree(char in[], char pre[], int inStrt, int inEnd) { static int preIndex = 0; if (inStrt > inEnd) return NULL; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ node* tNode = newNode(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, tNode->data); /* Using index in Inorder traversal, construct left and right subtress */ tNode->left = buildTree(in, pre, inStrt, inIndex - 1); tNode->right = buildTree(in, pre, inIndex + 1, inEnd); return tNode; } /* UTILITY FUNCTIONS */ /* Function to find index of value in arr[start...end] The function assumes that value is present in in[] */ int search(char arr[], int strt, int end, char value) { int i; for (i = strt; i <= end; i++) { if (arr[i] == value) return i; } } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ node* newNode(char data) { node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node); } /* This function is here just to test buildTree() */ void printInorder(node* node) { if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ cout<<node->data<<" "; /* now recur on right child */ printInorder(node->right); } /* Driver code */ int main() { char in[] = { 'D', 'B', 'E', 'A', 'F', 'C' }; char pre[] = { 'A', 'B', 'D', 'E', 'C', 'F' }; int len = sizeof(in) / sizeof(in[0]); node* root = buildTree(in, pre, 0, len - 1); /* Let us test the built tree by printing Inorder traversal */ cout << "Inorder traversal of the constructed tree is \n"; printInorder(root); } // This is code is contributed by rathbhupendra
linear
quadratic
/* C++ program to construct tree using inorder and preorder traversals */ #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { char data; struct Node* left; struct Node* right; }; struct Node* newNode(char data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } /* Recursive function to construct binary of size len from Inorder traversal in[] and Preorder traversal pre[]. Initial values of inStrt and inEnd should be 0 and len -1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree */ struct Node* buildTree(char in[], char pre[], int inStrt, int inEnd, unordered_map<char, int>& mp) { static int preIndex = 0; if (inStrt > inEnd) return NULL; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ char curr = pre[preIndex++]; struct Node* tNode = newNode(curr); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = mp[curr]; /* Using index in Inorder traversal, construct left and right subtress */ tNode->left = buildTree(in, pre, inStrt, inIndex - 1, mp); tNode->right = buildTree(in, pre, inIndex + 1, inEnd, mp); return tNode; } // This function mainly creates an unordered_map, then // calls buildTree() struct Node* buldTreeWrap(char in[], char pre[], int len) { // Store indexes of all items so that we // we can quickly find later unordered_map<char, int> mp; for (int i = 0; i < len; i++) mp[in[i]] = i; return buildTree(in, pre, 0, len - 1, mp); } /* This function is here just to test buildTree() */ void printInorder(struct Node* node) { if (node == NULL) return; printInorder(node->left); printf("%c ", node->data); printInorder(node->right); } /* Driver program to test above functions */ int main() { char in[] = { 'D', 'B', 'E', 'A', 'F', 'C' }; char pre[] = { 'A', 'B', 'D', 'E', 'C', 'F' }; int len = sizeof(in) / sizeof(in[0]); struct Node* root = buldTreeWrap(in, pre, len); /* Let us test the built tree by printing Inorder traversal */ printf("Inorder traversal of the constructed tree is \n"); printInorder(root); }
linear
linear
// C++ program to construct a tree using // inorder and preorder traversal #include<bits/stdc++.h> using namespace std; class TreeNode { public: int val; TreeNode* left; TreeNode* right; TreeNode(int x) { val = x; } }; set<TreeNode*> s; stack<TreeNode*> st; // Function to build tree using given traversal TreeNode* buildTree(int preorder[], int inorder[],int n) { TreeNode* root = NULL; for (int pre = 0, in = 0; pre < n;) { TreeNode* node = NULL; do { node = new TreeNode(preorder[pre]); if (root == NULL) { root = node; } if (st.size() > 0) { if (s.find(st.top()) != s.end()) { s.erase(st.top()); st.top()->right = node; st.pop(); } else { st.top()->left = node; } } st.push(node); } while (preorder[pre++] != inorder[in] && pre < n); node = NULL; while (st.size() > 0 && in < n && st.top()->val == inorder[in]) { node = st.top(); st.pop(); in++; } if (node != NULL) { s.insert(node); st.push(node); } } return root; } // Function to print tree in Inorder void printInorder(TreeNode* node) { if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ cout << node->val << " "; /* now recur on right child */ printInorder(node->right); } // Driver code int main() { int in[] = { 9, 8, 4, 2, 10, 5, 10, 1, 6, 3, 13, 12, 7 }; int pre[] = { 1, 2, 4, 8, 9, 5, 10, 10, 3, 6, 7, 12, 13 }; int len = sizeof(in)/sizeof(int); TreeNode *root = buildTree(pre, in, len); printInorder(root); return 0; } // This code is contributed by Arnab Kundu
linear
linear
/* program to construct tree using inorder and levelorder * traversals */ #include <bits/stdc++.h> using namespace std; /* A binary tree node */ struct Node { int key; struct Node *left, *right; }; /* Function to find index of value in arr[start...end] */ int search(int arr[], int strt, int end, int value) { for (int i = strt; i <= end; i++) if (arr[i] == value) return i; return -1; } // n is size of level[], m is size of in[] and m < n. This // function extracts keys from level[] which are present in // in[]. The order of extracted keys must be maintained int* extrackKeys(int in[], int level[], int m, int n) { int *newlevel = new int[m], j = 0; for (int i = 0; i < n; i++) if (search(in, 0, m - 1, level[i]) != -1) newlevel[j] = level[i], j++; return newlevel; } /* function that allocates a new node with the given key */ Node* newNode(int key) { Node* node = new Node; node->key = key; node->left = node->right = NULL; return (node); } /* Recursive function to construct binary tree of size n from Inorder traversal in[] and Level Order traversal level[]. inStrt and inEnd are start and end indexes of array in[] Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and levelorder do not form a tree */ Node* buildTree(int in[], int level[], int inStrt, int inEnd, int n) { // If start index is more than the end index if (inStrt > inEnd) return NULL; /* The first node in level order traversal is root */ Node* root = newNode(level[0]); /* If this node has no children then return */ if (inStrt == inEnd) return root; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, root->key); // Extract left subtree keys from level order traversal int* llevel = extrackKeys(in, level, inIndex, n); // Extract right subtree keys from level order traversal int* rlevel = extrackKeys(in + inIndex + 1, level, n - 1, n); /* construct left and right subtrees */ root->left = buildTree(in, llevel, inStrt, inIndex - 1, inIndex - inStrt); root->right = buildTree(in, rlevel, inIndex + 1, inEnd, inEnd - inIndex); // Free memory to avoid memory leak delete[] llevel; delete[] rlevel; return root; } /* utility function to print inorder traversal of binary * tree */ void printInorder(Node* node) { if (node == NULL) return; printInorder(node->left); cout << node->key << " "; printInorder(node->right); } /* Driver program to test above functions */ int main() { int in[] = { 4, 8, 10, 12, 14, 20, 22 }; int level[] = { 20, 8, 22, 4, 12, 10, 14 }; int n = sizeof(in) / sizeof(in[0]); Node* root = buildTree(in, level, 0, n - 1, n); /* Let us test the built tree by printing Inorder * traversal */ cout << "Inorder traversal of the constructed tree is " "\n"; printInorder(root); return 0; }
linear
cubic
// C++ program to create a Complete Binary tree from its Linked List // Representation #include <iostream> #include <string> #include <queue> using namespace std; // Linked list node struct ListNode { int data; ListNode* next; }; // Binary tree node structure struct BinaryTreeNode { int data; BinaryTreeNode *left, *right; }; // Function to insert a node at the beginning of the Linked List void push(struct ListNode** head_ref, int new_data) { // allocate node and assign data struct ListNode* new_node = new ListNode; new_node->data = new_data; // link the old list off the new node new_node->next = (*head_ref); // move the head to point to the new node (*head_ref) = new_node; } // method to create a new binary tree node from the given data BinaryTreeNode* newBinaryTreeNode(int data) { BinaryTreeNode *temp = new BinaryTreeNode; temp->data = data; temp->left = temp->right = NULL; return temp; } // converts a given linked list representing a complete binary tree into the // linked representation of binary tree. void convertList2Binary(ListNode *head, BinaryTreeNode* &root) { // queue to store the parent nodes queue<BinaryTreeNode *> q; // Base Case if (head == NULL) { root = NULL; // Note that root is passed by reference return; } // 1.) The first node is always the root node, and add it to the queue root = newBinaryTreeNode(head->data); q.push(root); // advance the pointer to the next node head = head->next; // until the end of linked list is reached, do the following steps while (head) { // 2.a) take the parent node from the q and remove it from q BinaryTreeNode* parent = q.front(); q.pop(); // 2.c) take next two nodes from the linked list. We will add // them as children of the current parent node in step 2.b. Push them // into the queue so that they will be parents to the future nodes BinaryTreeNode *leftChild = NULL, *rightChild = NULL; leftChild = newBinaryTreeNode(head->data); q.push(leftChild); head = head->next; if (head) { rightChild = newBinaryTreeNode(head->data); q.push(rightChild); head = head->next; } // 2.b) assign the left and right children of parent parent->left = leftChild; parent->right = rightChild; } } // Utility function to traverse the binary tree after conversion void inorderTraversal(BinaryTreeNode* root) { if (root) { inorderTraversal( root->left ); cout << root->data << " "; inorderTraversal( root->right ); } } // Driver program to test above functions int main() { // create a linked list shown in above diagram struct ListNode* head = NULL; push(&head, 36); /* Last node of Linked List */ push(&head, 30); push(&head, 25); push(&head, 15); push(&head, 12); push(&head, 10); /* First node of Linked List */ BinaryTreeNode *root; convertList2Binary(head, root); cout << "Inorder Traversal of the constructed Binary Tree is: \n"; inorderTraversal(root); return 0; }
np
linear
// CPP program to construct binary // tree from given array in level // order fashion Tree Node #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node* left, * right; }; /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } // Function to insert nodes in level order Node* insertLevelOrder(int arr[], int i, int n) { Node *root = nullptr; // Base case for recursion if (i < n) { root = newNode(arr[i]); // insert left child root->left = insertLevelOrder(arr, 2 * i + 1, n); // insert right child root->right = insertLevelOrder(arr, 2 * i + 2, n); } return root; } // Function to print tree nodes in // InOrder fashion void inOrder(Node* root) { if (root != NULL) { inOrder(root->left); cout << root->data <<" "; inOrder(root->right); } } // Driver program to test above function int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 6, 6, 6 }; int n = sizeof(arr)/sizeof(arr[0]); Node* root = insertLevelOrder(arr, 0, n); inOrder(root); } // This code is contributed by Chhavi and improved by Thangaraj
linear
linear
// Program for construction of Full Binary Tree #include <bits/stdc++.h> using namespace std; // A binary tree node has data, pointer to left child // and a pointer to right child class node { public: int data; node* left; node* right; }; // A utility function to create a node node* newNode(int data) { node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // A recursive function to construct Full from pre[] and // post[]. preIndex is used to keep track of index in pre[]. // l is low index and h is high index for the current // subarray in post[] node* constructTreeUtil(int pre[], int post[], int* preIndex, int l, int h, int size) { // Base case if (*preIndex >= size || l > h) return NULL; // The first node in preorder traversal is root. So take // the node at preIndex from preorder and make it root, // and increment preIndex node* root = newNode(pre[*preIndex]); ++*preIndex; // If the current subarray has only one element, no need // to recur if (l == h) return root; // Search the next element of pre[] in post[] int i; for (i = l; i <= h; ++i) if (pre[*preIndex] == post[i]) break; // Use the index of element found in postorder to divide // postorder array in two parts. Left subtree and right // subtree if (i <= h) { root->left = constructTreeUtil(pre, post, preIndex, l, i, size); root->right = constructTreeUtil(pre, post, preIndex, i + 1, h - 1, size); } return root; } // The main function to construct Full Binary Tree from // given preorder and postorder traversals. This function // mainly uses constructTreeUtil() node* constructTree(int pre[], int post[], int size) { int preIndex = 0; return constructTreeUtil(pre, post, &preIndex, 0, size - 1, size); } // A utility function to print inorder traversal of a Binary // Tree void printInorder(node* node) { if (node == NULL) return; printInorder(node->left); cout << node->data << " "; printInorder(node->right); } // Driver program to test above functions int main() { int pre[] = { 1, 2, 4, 8, 9, 5, 3, 6, 7 }; int post[] = { 8, 9, 4, 5, 2, 6, 7, 3, 1 }; int size = sizeof(pre) / sizeof(pre[0]); node* root = constructTree(pre, post, size); cout << "Inorder traversal of the constructed tree: \n"; printInorder(root); return 0; }
logn
constant
// C++ program to construct full binary tree // using its preorder traversal and preorder // traversal of its mirror tree #include<bits/stdc++.h> using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; // Utility function to create a new tree node Node* newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // A utility function to print inorder traversal // of a Binary Tree void printInorder(Node* node) { if (node == NULL) return; printInorder(node->left); printf("%d ", node->data); printInorder(node->right); } // A recursive function to construct Full binary tree // from pre[] and preM[]. preIndex is used to keep // track of index in pre[]. l is low index and h is high //index for the current subarray in preM[] Node* constructBinaryTreeUtil(int pre[], int preM[], int &preIndex, int l,int h,int size) { // Base case if (preIndex >= size || l > h) return NULL; // The first node in preorder traversal is root. // So take the node at preIndex from preorder and // make it root, and increment preIndex Node* root = newNode(pre[preIndex]); ++(preIndex); // If the current subarray has only one element, // no need to recur if (l == h) return root; // Search the next element of pre[] in preM[] int i; for (i = l; i <= h; ++i) if (pre[preIndex] == preM[i]) break; // construct left and right subtrees recursively if (i <= h) { root->left = constructBinaryTreeUtil (pre, preM, preIndex, i, h, size); root->right = constructBinaryTreeUtil (pre, preM, preIndex, l+1, i-1, size); } // return root return root; } // function to construct full binary tree // using its preorder traversal and preorder // traversal of its mirror tree void constructBinaryTree(Node* root,int pre[], int preMirror[], int size) { int preIndex = 0; int preMIndex = 0; root = constructBinaryTreeUtil(pre,preMirror, preIndex,0,size-1,size); printInorder(root); } // Driver program to test above functions int main() { int preOrder[] = {1,2,4,5,3,6,7}; int preOrderMirror[] = {1,3,7,6,2,5,4}; int size = sizeof(preOrder)/sizeof(preOrder[0]); Node* root = new Node; constructBinaryTree(root,preOrder,preOrderMirror,size); return 0; }
linear
quadratic
// A program to construct Binary Tree from preorder traversal #include<bits/stdc++.h> // A binary tree node structure struct node { int data; struct node *left; struct node *right; }; // Utility function to create a new Binary Tree node struct node* newNode (int data) { struct node *temp = new struct node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } /* A recursive function to create a Binary Tree from given pre[] preLN[] arrays. The function returns root of tree. index_ptr is used to update index values in recursive calls. index must be initially passed as 0 */ struct node *constructTreeUtil(int pre[], char preLN[], int *index_ptr, int n) { int index = *index_ptr; // store the current value of index in pre[] // Base Case: All nodes are constructed if (index == n) return NULL; // Allocate memory for this node and increment index for // subsequent recursive calls struct node *temp = newNode ( pre[index] ); (*index_ptr)++; // If this is an internal node, construct left and // right subtrees and link the subtrees if (preLN[index] == 'N') { temp->left = constructTreeUtil(pre, preLN, index_ptr, n); temp->right = constructTreeUtil(pre, preLN, index_ptr, n); } return temp; } // A wrapper over constructTreeUtil() struct node *constructTree(int pre[], char preLN[], int n) { /* Initialize index as 0. Value of index is used in recursion to maintain the current index in pre[] and preLN[] arrays. */ int index = 0; return constructTreeUtil (pre, preLN, &index, n); } // This function is used only for testing void printInorder (struct node* node) { if (node == NULL) return; // First recur on left child printInorder (node->left); // Print the data of node printf("%d ", node->data); // Now recur on right child printInorder (node->right); } // Driver code int main() { struct node *root = NULL; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ int pre[] = {10, 30, 20, 5, 15}; char preLN[] = {'N', 'N', 'L', 'L', 'L'}; int n = sizeof(pre)/sizeof(pre[0]); // construct the above tree root = constructTree (pre, preLN, n); // Test the constructed tree printf("Inorder Traversal of the Constructed Binary Tree: \n"); printInorder (root); return 0; }
linear
linear
// A program to construct Binary Tree from preorder // traversal #include <bits/stdc++.h> using namespace std; // A binary tree node structure struct node { int data; struct node* left; struct node* right; node(int x) { data = x; left = right = NULL; } }; struct node* constructTree(int pre[], char preLN[], int n) { // Taking an empty Stack stack<node*> st; // Setting up root node node* root = new node(pre[0]); // Checking if root is not leaf node if (preLN[0] != 'L') st.push(root); // Iterating over the given node values for (int i = 1; i < n; i++) { node* temp = new node(pre[i]); // Checking if the left position is NULL or not if (!st.top()->left) { st.top()->left = temp; // Checking for leaf node if (preLN[i] != 'L') st.push(temp); } // Checking if the right position is NULL or not else if (!st.top()->right) { st.top()->right = temp; if (preLN[i] != 'L') // Checking for leaf node st.push(temp); } // If left and right of top node is already filles else { while (st.top()->left && st.top()->right) st.pop(); st.top()->right = temp; // Checking for leaf node if (preLN[i] != 'L') st.push(temp); } } // Returning the root of tree return root; } // This function is used only for testing void printInorder(struct node* node) { if (node == NULL) return; // First recur on left child printInorder(node->left); // Print the data of node printf("%d ", node->data); // Now recur on right child printInorder(node->right); } // Driver code int main() { struct node* root = NULL; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ int pre[] = { 10, 30, 20, 5, 15 }; char preLN[] = { 'N', 'N', 'L', 'L', 'L' }; int n = sizeof(pre) / sizeof(pre[0]); // construct the above tree root = constructTree(pre, preLN, n); // Test the constructed tree printf("Inorder Traversal of the Constructed Binary Tree: \n"); printInorder(root); return 0; } // This code is contributed by shubhamrajput6156
linear
linear
// Given an ancestor matrix for binary tree, construct // the tree. #include <bits/stdc++.h> using namespace std; # define N 6 /* A binary tree node */ struct Node { int data; Node *left, *right; }; /* Helper function to create a new node */ Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Constructs tree from ancestor matrix Node* ancestorTree(int mat[][N]) { // Binary array to determine whether // parent is set for node i or not int parent[N] = {0}; // Root will store the root of the constructed tree Node* root = NULL; // Create a multimap, sum is used as key and row // numbers are used as values multimap<int, int> mm; for (int i = 0; i < N; i++) { int sum = 0; // Initialize sum of this row for (int j = 0; j < N; j++) sum += mat[i][j]; // insert(sum, i) pairs into the multimap mm.insert(pair<int, int>(sum, i)); } // node[i] will store node for i in constructed tree Node* node[N]; // Traverse all entries of multimap. Note that values // are accessed in increasing order of sum for (auto it = mm.begin(); it != mm.end(); ++it) { // create a new node for every value node[it->second] = newNode(it->second); // To store last processed node. This node will be // root after loop terminates root = node[it->second]; // if non-leaf node if (it->first != 0) { // traverse row 'it->second' in the matrix for (int i = 0; i < N; i++) { // if parent is not set and ancestor exits if (!parent[i] && mat[it->second][i]) { // check for unoccupied left/right node // and set parent of node i if (!node[it->second]->left) node[it->second]->left = node[i]; else node[it->second]->right = node[i]; parent[i] = 1; } } } } return root; } /* Given a binary tree, print its nodes in inorder */ void printInorder(Node* node) { if (node == NULL) return; printInorder(node->left); printf("%d ", node->data); printInorder(node->right); } // Driver code int main() { int mat[N][N] = {{ 0, 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 1, 0 }, { 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 1, 1, 0 } }; Node* root = ancestorTree(mat); cout << "Inorder traversal of tree is \n"; // Function call printInorder(root); return 0; }
quadratic
quadratic
// C++ program to construct ancestor matrix for // given tree. #include<bits/stdc++.h> using namespace std; #define MAX 100 /* A binary tree node */ struct Node { int data; Node *left, *right; }; // Creating a global boolean matrix for simplicity bool mat[MAX][MAX]; // anc[] stores all ancestors of current node. This // function fills ancestors for all nodes. // It also returns size of tree. Size of tree is // used to print ancestor matrix. int ancestorMatrixRec(Node *root, vector<int> &anc) { /* base case */ if (root == NULL) return 0;; // Update all ancestors of current node int data = root->data; for (int i=0; i<anc.size(); i++) mat[anc[i]][data] = true; // Push data to list of ancestors anc.push_back(data); // Traverse left and right subtrees int l = ancestorMatrixRec(root->left, anc); int r = ancestorMatrixRec(root->right, anc); // Remove data from list the list of ancestors // as all descendants of it are processed now. anc.pop_back(); return l+r+1; } // This function mainly calls ancestorMatrixRec() void ancestorMatrix(Node *root) { // Create an empty ancestor array vector<int> anc; // Fill ancestor matrix and find size of // tree. int n = ancestorMatrixRec(root, anc); // Print the filled values for (int i=0; i<n; i++) { for (int j=0; j<n; j++) cout << mat[i][j] << " "; cout << endl; } } /* Helper function to create a new node */ Node* newnode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } /* Driver program to test above functions*/ int main() { /* Construct the following binary tree 5 / \ 1 2 / \ / 0 4 3 */ Node *root = newnode(5); root->left = newnode(1); root->right = newnode(2); root->left->left = newnode(0); root->left->right = newnode(4); root->right->left = newnode(3); ancestorMatrix(root); return 0; }
quadratic
quadratic
// C++ program to construct ancestor matrix for // given tree. #include<bits/stdc++.h> using namespace std; #define size 6 int M[size][size]={0}; /* A binary tree node */ struct Node { int data; Node *left, *right; }; /* Helper function to create a new node */ Node* newnode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } void printMatrix(){ for(int i=0;i<size;i++){ for(int j=0;j<size;j++) cout<<M[i][j]<<" "; cout<<endl; } } //First PreOrder Traversal void MatrixUtil(Node *root,int index){ if(root==NULL)return; int preData=root->data; //Since there is no ancestor for root node, // so we doesn't assign it's value as 1 if(index==-1)index=root->data; else M[index][preData]=1; MatrixUtil(root->left,preData); MatrixUtil(root->right,preData); } void Matrix(Node *root){ // Call Func MatrixUtil MatrixUtil(root,-1); //Applying Transitive Closure for the given Matrix for(int i=0;i<size;i++){ for (int j = 0;j< size; j++) { for(int k=0;k<size;k++) M[j][k]=M[j][k]||(M[j][i]&&M[i][k]); } } //Printing Matrix printMatrix(); } /* Driver program to test above functions*/ int main() { Node *root = newnode(5); root->left = newnode(1); root->right = newnode(2); root->left->left = newnode(0); root->left->right = newnode(4); root->right->left = newnode(3); Matrix(root); return 0; }
quadratic
quadratic
/* C++ program to construct tree from inorder traversal */ #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: int data; node* left; node* right; }; /* Prototypes of a utility function to get the maximum value in inorder[start..end] */ int max(int inorder[], int strt, int end); /* A utility function to allocate memory for a node */ node* newNode(int data); /* Recursive function to construct binary of size len from Inorder traversal inorder[]. Initial values of start and end should be 0 and len -1. */ node* buildTree (int inorder[], int start, int end) { if (start > end) return NULL; /* Find index of the maximum element from Binary Tree */ int i = max (inorder, start, end); /* Pick the maximum value and make it root */ node *root = newNode(inorder[i]); /* If this is the only element in inorder[start..end], then return it */ if (start == end) return root; /* Using index in Inorder traversal, construct left and right subtress */ root->left = buildTree (inorder, start, i - 1); root->right = buildTree (inorder, i + 1, end); return root; } /* UTILITY FUNCTIONS */ /* Function to find index of the maximum value in arr[start...end] */ int max (int arr[], int strt, int end) { int i, max = arr[strt], maxind = strt; for(i = strt + 1; i <= end; i++) { if(arr[i] > max) { max = arr[i]; maxind = i; } } return maxind; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ node* newNode (int data) { node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return Node; } /* This function is here just to test buildTree() */ void printInorder (node* node) { if (node == NULL) return; /* first recur on left child */ printInorder (node->left); /* then print the data of node */ cout<<node->data<<" "; /* now recur on right child */ printInorder (node->right); } /* Driver code*/ int main() { /* Assume that inorder traversal of following tree is given 40 / \ 10 30 / \ 5 28 */ int inorder[] = {5, 10, 40, 30, 28}; int len = sizeof(inorder)/sizeof(inorder[0]); node *root = buildTree(inorder, 0, len - 1); /* Let us test the built tree by printing Inorder traversal */ cout << "Inorder traversal of the constructed tree is \n"; printInorder(root); return 0; } // This is code is contributed by rathbhupendra
linear
quadratic
// C++ program to construct a Binary Tree from parent array #include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node* left = NULL; struct Node* right = NULL; Node() {} Node(int x) { data = x; } }; // Function to construct binary tree from parent array. Node* createTree(int parent[], int n) { // Create an array to store the reference // of all newly created nodes corresponding // to node value vector<Node*> ref; // This root represent the root of the // newly constructed tree Node* root = new Node(); // Create n new tree nodes, each having // a value from 0 to n-1, and store them // in ref for (int i = 0; i < n; i++) { Node* temp = new Node(i); ref.push_back(temp); } // Traverse the parent array and build the tree for (int i = 0; i < n; i++) { // If the parent is -1, set the root // to the current node having // the value i which is stored in ref[i] if (parent[i] == -1) { root = ref[i]; } else { // Check if the parent's left child // is NULL then map the left child // to its parent. if (ref[parent[i]]->left == NULL) ref[parent[i]]->left = ref[i]; else ref[parent[i]]->right = ref[i]; } } // Return the root of the newly constructed tree return root; } // Function for inorder traversal void inorder(Node* root) { if (root != NULL) { inorder(root->left); cout << root->data << " "; inorder(root->right); } } // Driver code int main() { int parent[] = { -1, 0, 0, 1, 1, 3, 5 }; int n = sizeof parent / sizeof parent[0]; Node* root = createTree(parent, n); cout << "Inorder Traversal of constructed tree\n"; inorder(root); return 0; }
linear
linear
/* C++ program to construct tree using inorder and postorder traversals */ #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; // Utility function to create a new node Node* newNode(int data); /* Prototypes for utility functions */ int search(int arr[], int strt, int end, int value); /* Recursive function to construct binary of size n from Inorder traversal in[] and Postorder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */ Node* buildUtil(int in[], int post[], int inStrt, int inEnd, int* pIndex) { // Base case if (inStrt > inEnd) return NULL; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ Node* node = newNode(post[*pIndex]); (*pIndex)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = search(in, inStrt, inEnd, node->data); /* Using index in Inorder traversal, construct left and right subtrees */ node->right = buildUtil(in, post, iIndex + 1, inEnd, pIndex); node->left = buildUtil(in, post, inStrt, iIndex - 1, pIndex); return node; } // This function mainly initializes index of root // and calls buildUtil() Node* buildTree(int in[], int post[], int n) { int pIndex = n - 1; return buildUtil(in, post, 0, n - 1, &pIndex); } /* Function to find index of value in arr[start...end] The function assumes that value is postsent in in[] */ int search(int arr[], int strt, int end, int value) { int i; for (i = strt; i <= end; i++) { if (arr[i] == value) break; } return i; } /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } /* This function is here just to test */ void preOrder(Node* node) { if (node == NULL) return; printf("%d ", node->data); preOrder(node->left); preOrder(node->right); } // Driver code int main() { int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = sizeof(in) / sizeof(in[0]); Node* root = buildTree(in, post, n); cout << "Preorder of the constructed tree : \n"; preOrder(root); return 0; }
linear
quadratic
/* C++ program to construct tree using inorder and postorder traversals */ #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; // Utility function to create a new node Node* newNode(int data); /* Recursive function to construct binary of size n from Inorder traversal in[] and Postorder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */ Node* buildUtil(int in[], int post[], int inStrt, int inEnd, int* pIndex, unordered_map<int, int>& mp) { // Base case if (inStrt > inEnd) return NULL; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ int curr = post[*pIndex]; Node* node = newNode(curr); (*pIndex)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = mp[curr]; /* Using index in Inorder traversal, construct left and right subtrees */ node->right = buildUtil(in, post, iIndex + 1, inEnd, pIndex, mp); node->left = buildUtil(in, post, inStrt, iIndex - 1, pIndex, mp); return node; } // This function mainly creates an unordered_map, then // calls buildTreeUtil() struct Node* buildTree(int in[], int post[], int len) { // Store indexes of all items so that we // we can quickly find later unordered_map<int, int> mp; for (int i = 0; i < len; i++) mp[in[i]] = i; int index = len - 1; // Index in postorder return buildUtil(in, post, 0, len - 1, &index, mp); } /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } /* This function is here just to test */ void preOrder(Node* node) { if (node == NULL) return; printf("%d ", node->data); preOrder(node->left); preOrder(node->right); } // Driver code int main() { int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = sizeof(in) / sizeof(in[0]); Node* root = buildTree(in, post, n); cout << "Preorder of the constructed tree : \n"; preOrder(root); return 0; }
linear
linear
// C++ program for above approach #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; Node(int x) { data = x; left = right = NULL; } }; /*Tree building function*/ Node *buildTree(int in[], int post[], int n) { // Create Stack of type Node* stack<Node*> st; // Create Set of type Node* set<Node*> s; // Initialise postIndex with n - 1 int postIndex = n - 1; // Initialise root with NULL Node* root = NULL; for (int p = n - 1, i = n - 1; p>=0;) { // Initialise node with NULL Node* node = NULL; // Run do-while loop do { // Initialise node with // new Node(post[p]); node = new Node(post[p]); // Check is root is // equal to NULL if (root == NULL) { root = node; } // If size of set // is greater than 0 if (st.size() > 0) { // If st.top() is present in the // set s if (s.find(st.top()) != s.end()) { s.erase(st.top()); st.top()->left = node; st.pop(); } else { st.top()->right = node; } } st.push(node); } while (post[p--] != in[i] && p >=0); node = NULL; // If the stack is not empty and // st.top()->data is equal to in[i] while (st.size() > 0 && i>=0 && st.top()->data == in[i]) { node = st.top(); // Pop elements from stack st.pop(); i--; } // if node not equal to NULL if (node != NULL) { s.insert(node); st.push(node); } } // Return root return root; } /* for print preOrder Traversal */ void preOrder(Node* node) { if (node == NULL) return; printf("%d ", node->data); preOrder(node->left); preOrder(node->right); } // Driver Code int main() { int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = sizeof(in) / sizeof(in[0]); // Function Call Node* root = buildTree(in, post, n); cout << "Preorder of the constructed tree : \n"; // Function Call for preOrder preOrder(root); return 0; }
linear
linear
// C++ program to create a doubly linked list out // of given a ternary tree. #include <bits/stdc++.h> using namespace std; /* A ternary tree */ struct Node { int data; struct Node *left, *middle, *right; }; /* Helper function that allocates a new node with the given data and assign NULL to left, middle and right pointers.*/ Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->middle = node->right = NULL; return node; } /* Utility function that constructs doubly linked list by inserting current node at the end of the doubly linked list by using a tail pointer */ void push(Node** tail_ref, Node* node) { // initialize tail pointer if (*tail_ref == NULL) { *tail_ref = node; // set left, middle and right child to point // to NULL node->left = node->middle = node->right = NULL; return; } // insert node in the end using tail pointer (*tail_ref)->right = node; // set prev of node node->left = (*tail_ref); // set middle and right child to point to NULL node->right = node->middle = NULL; // now tail pointer will point to inserted node (*tail_ref) = node; } /* Create a doubly linked list out of given a ternary tree. by traversing the tree in preorder fashion. */ void TernaryTreeToList(Node* root, Node** head_ref) { // Base case if (root == NULL) return; //create a static tail pointer static Node* tail = NULL; // store left, middle and right nodes // for future calls. Node* left = root->left; Node* middle = root->middle; Node* right = root->right; // set head of the doubly linked list // head will be root of the ternary tree if (*head_ref == NULL) *head_ref = root; // push current node in the end of DLL push(&tail, root); //recurse for left, middle and right child TernaryTreeToList(left, head_ref); TernaryTreeToList(middle, head_ref); TernaryTreeToList(right, head_ref); } // Utility function for printing double linked list. void printList(Node* head) { printf("Created Double Linked list is:\n"); while (head) { printf("%d ", head->data); head = head->right; } } // Driver program to test above functions int main() { // Constructing ternary tree as shown in above figure Node* root = newNode(30); root->left = newNode(5); root->middle = newNode(11); root->right = newNode(63); root->left->left = newNode(1); root->left->middle = newNode(4); root->left->right = newNode(8); root->middle->left = newNode(6); root->middle->middle = newNode(7); root->middle->right = newNode(15); root->right->left = newNode(31); root->right->middle = newNode(55); root->right->right = newNode(65); Node* head = NULL; TernaryTreeToList(root, &head); printList(head); return 0; }
linear
linear
// C++ program to create a tree with left child // right sibling representation. #include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node* next; struct Node* child; }; // Creating new Node Node* newNode(int data) { Node* newNode = new Node; newNode->next = newNode->child = NULL; newNode->data = data; return newNode; } // Adds a sibling to a list with starting with n Node* addSibling(Node* n, int data) { if (n == NULL) return NULL; while (n->next) n = n->next; return (n->next = newNode(data)); } // Add child Node to a Node Node* addChild(Node* n, int data) { if (n == NULL) return NULL; // Check if child list is not empty. if (n->child) return addSibling(n->child, data); else return (n->child = newNode(data)); } // Traverses tree in level order void traverseTree(Node* root) { // Corner cases if (root == NULL) return; cout << root->data << " "; if (root->child == NULL) return; // Create a queue and enqueue root queue<Node*> q; Node* curr = root->child; q.push(curr); while (!q.empty()) { // Take out an item from the queue curr = q.front(); q.pop(); // Print next level of taken out item and enqueue // next level's children while (curr != NULL) { cout << curr->data << " "; if (curr->child != NULL) { q.push(curr->child); } curr = curr->next; } } } // Driver code int main() { Node* root = newNode(10); Node* n1 = addChild(root, 2); Node* n2 = addChild(root, 3); Node* n3 = addChild(root, 4); Node* n4 = addChild(n3, 6); Node* n5 = addChild(root, 5); Node* n6 = addChild(n5, 7); Node* n7 = addChild(n5, 8); Node* n8 = addChild(n5, 9); traverseTree(root); return 0; }
linear
linear
/* C++ program to construct a binary tree from the given string */ #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } /* This function is here just to test */ void preOrder(Node* node) { if (node == NULL) return; printf("%d ", node->data); preOrder(node->left); preOrder(node->right); } // function to return the index of close parenthesis int findIndex(string str, int si, int ei) { if (si > ei) return -1; // Inbuilt stack stack<char> s; for (int i = si; i <= ei; i++) { // if open parenthesis, push it if (str[i] == '(') s.push(str[i]); // if close parenthesis else if (str[i] == ')') { if (s.top() == '(') { s.pop(); // if stack is empty, this is // the required index if (s.empty()) return i; } } } // if not found return -1 return -1; } // function to construct tree from string Node* treeFromString(string str, int si, int ei) { // Base case if (si > ei) return NULL; int num = 0; // In case the number is having more than 1 digit while(si <= ei && str[si] >= '0' && str[si] <= '9') { num *= 10; num += (str[si] - '0'); si++; } // new root Node* root = newNode(num); int index = -1; // if next char is '(' find the index of // its complement ')' if (si <= ei && str[si] == '(') index = findIndex(str, si, ei); // if index found if (index != -1) { // call for left subtree root->left = treeFromString(str, si + 1, index - 1); // call for right subtree root->right = treeFromString(str, index + 2, ei - 1); } return root; } // Driver Code int main() { string str = "4(2(3)(1))(6(5))"; Node* root = treeFromString(str, 0, str.length() - 1); preOrder(root); }
linear
quadratic
// A simple inorder traversal based // program to convert a Binary Tree to DLL #include <bits/stdc++.h> using namespace std; // A tree node class node { public: int data; node *left, *right; }; // A utility function to create // a new tree node node *newNode(int data) { node *Node = new node(); Node->data = data; Node->left = Node->right = NULL; return(Node); } // Standard Inorder traversal of tree void inorder(node *root) { if (root != NULL) { inorder(root->left); cout << "\t" << root->data; inorder(root->right); } } // Changes left pointers to work as // previous pointers in converted DLL // The function simply does inorder // traversal of Binary Tree and updates // left pointer using previously visited node void fixPrevPtr(node *root) { static node *pre = NULL; if (root != NULL) { fixPrevPtr(root->left); root->left = pre; pre = root; fixPrevPtr(root->right); } } // Changes right pointers to work // as next pointers in converted DLL node *fixNextPtr(node *root) { node *prev = NULL; // Find the right most node // in BT or last node in DLL while (root && root->right != NULL) root = root->right; // Start from the rightmost node, // traverse back using left pointers. // While traversing, change right pointer of nodes. while (root && root->left != NULL) { prev = root; root = root->left; root->right = prev; } // The leftmost node is head // of linked list, return it return (root); } // The main function that converts // BST to DLL and returns head of DLL node *BTToDLL(node *root) { // Set the previous pointer fixPrevPtr(root); // Set the next pointer and return head of DLL return fixNextPtr(root); } // Traverses the DLL from left to right void printList(node *root) { while (root != NULL) { cout<<"\t"<<root->data; root = root->right; } } // Driver code int main(void) { // Let us create the tree // shown in above diagram node *root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); cout<<"\n\t\tInorder Tree Traversal\n\n"; inorder(root); node *head = BTToDLL(root); cout << "\n\n\t\tDLL Traversal\n\n"; printList(head); return 0; } // This code is contributed by rathbhupendra
linear
linear
// A C++ program for in-place conversion of Binary Tree to // DLL #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, and left and right pointers */ struct node { int data; node* left; node* right; }; node * bToDLL(node *root) { stack<pair<node*, int>> s; s.push({root, 0}); vector<int> res; bool flag = true; node* head = NULL; node* prev = NULL; while(!s.empty()) { auto x = s.top(); node* t = x.first; int state = x.second; s.pop(); if(state == 3 or t == NULL) continue; s.push({t, state+1}); if(state == 0) s.push({t->left, 0}); else if(state == 1) { if(prev) prev->right = t; t->left = prev; prev = t; if(flag) { head = t; flag = false; } } else if(state == 2) s.push({t->right, 0}); } return head; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ node* newNode(int data) { node* new_node = new node; new_node->data = data; new_node->left = new_node->right = NULL; return (new_node); } /* Function to print nodes in a given doubly linked list */ void printList(node* node) { while (node != NULL) { cout << node->data << " "; node = node->right; } } // Driver Code int main() { // Let us create the tree shown in above diagram node* root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); // Convert to DLL node* head = bToDLL(root); // Print the converted list printList(head); return 0; }
linear
linear
// C++ program to convert a given Binary Tree to Doubly Linked List #include <bits/stdc++.h> // Structure for tree and linked list struct Node { int data; Node *left, *right; }; // Utility function for allocating node for Binary // Tree. Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } // A simple recursive function to convert a given // Binary tree to Doubly Linked List // root --> Root of Binary Tree // head --> Pointer to head node of created doubly linked list void BToDLL(Node* root, Node*& head) { // Base cases if (root == NULL) return; // Recursively convert right subtree BToDLL(root->right, head); // insert root into DLL root->right = head; // Change left pointer of previous head if (head != NULL) head->left = root; // Change head of Doubly linked list head = root; // Recursively convert left subtree BToDLL(root->left, head); } // Utility function for printing double linked list. void printList(Node* head) { printf("Extracted Double Linked list is:\n"); while (head) { printf("%d ", head->data); head = head->right; } } // Driver program to test above function int main() { /* Constructing below tree 5 / \ 3 6 / \ \ 1 4 8 / \ / \ 0 2 7 9 */ Node* root = newNode(5); root->left = newNode(3); root->right = newNode(6); root->left->left = newNode(1); root->left->right = newNode(4); root->right->right = newNode(8); root->left->left->left = newNode(0); root->left->left->right = newNode(2); root->right->right->left = newNode(7); root->right->right->right = newNode(9); Node* head = NULL; BToDLL(root, head); printList(head); return 0; }
linear
linear
// C++ program to convert a binary tree // to its mirror #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } /* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \ 3 1 is changed to... 4 / \ 5 2 / \ 1 3 */ void mirror(struct Node* node) { if (node == NULL) return; else { struct Node* temp; /* do the subtrees */ mirror(node->left); mirror(node->right); /* swap the pointers in this node */ temp = node->left; node->left = node->right; node->right = temp; } } /* Helper function to print Inorder traversal.*/ void inOrder(struct Node* node) { if (node == NULL) return; inOrder(node->left); cout << node->data << " "; inOrder(node->right); } // Driver Code int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print inorder traversal of the input tree */ cout << "Inorder traversal of the constructed" << " tree is" << endl; inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ cout << "\nInorder traversal of the mirror tree" << " is \n"; inOrder(root); return 0; } // This code is contributed by Akanksha Rai
linear
linear
// Iterative CPP program to convert a Binary // Tree to its mirror #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } /* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \ 1 3 is changed to... 4 / \ 5 2 / \ 3 1 */ void mirror(Node* root) { if (root == NULL) return; queue<Node*> q; q.push(root); // Do BFS. While doing BFS, keep swapping // left and right children while (!q.empty()) { // pop top node from queue Node* curr = q.front(); q.pop(); // swap left child with right child swap(curr->left, curr->right); // push left and right children if (curr->left) q.push(curr->left); if (curr->right) q.push(curr->right); } } /* Helper function to print Inorder traversal.*/ void inOrder(struct Node* node) { if (node == NULL) return; inOrder(node->left); cout << node->data << " "; inOrder(node->right); } /* Driver program to test mirror() */ int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print inorder traversal of the input tree */ cout << "Inorder traversal of the" " constructed tree is \n"; inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ cout << "\nInorder traversal of the " "mirror tree is \n"; inOrder(root); return 0; }
linear
linear
/* c++ program to convert Binary Tree into Doubly Linked List where the nodes are represented spirally. */ #include <bits/stdc++.h> using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; /* Given a reference to the head of a list and a node, inserts the node on the front of the list. */ void push(Node** head_ref, Node* node) { // Make right of given node as head and left as // NULL node->right = (*head_ref); node->left = NULL; // change left of head node to given node if ((*head_ref) != NULL) (*head_ref)->left = node ; // move the head to point to the given node (*head_ref) = node; } // Function to prints contents of DLL void printList(Node *node) { while (node != NULL) { cout << node->data << " "; node = node->right; } } /* Function to print corner node at each level */ void spiralLevelOrder(Node *root) { // Base Case if (root == NULL) return; // Create an empty deque for doing spiral // level order traversal and enqueue root deque<Node*> q; q.push_front(root); // create a stack to store Binary Tree nodes // to insert into DLL later stack<Node*> stk; int level = 0; while (!q.empty()) { // nodeCount indicates number of Nodes // at current level. int nodeCount = q.size(); // Dequeue all Nodes of current level and // Enqueue all Nodes of next level if (level&1) //odd level { while (nodeCount > 0) { // dequeue node from front & push it to // stack Node *node = q.front(); q.pop_front(); stk.push(node); // insert its left and right children // in the back of the deque if (node->left != NULL) q.push_back(node->left); if (node->right != NULL) q.push_back(node->right); nodeCount--; } } else //even level { while (nodeCount > 0) { // dequeue node from the back & push it // to stack Node *node = q.back(); q.pop_back(); stk.push(node); // inserts its right and left children // in the front of the deque if (node->right != NULL) q.push_front(node->right); if (node->left != NULL) q.push_front(node->left); nodeCount--; } } level++; } // head pointer for DLL Node* head = NULL; // pop all nodes from stack and // push them in the beginning of the list while (!stk.empty()) { push(&head, stk.top()); stk.pop(); } cout << "Created DLL is:\n"; printList(head); } // Utility function to create a new tree Node Node* newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver program to test above functions int main() { // Let us create binary tree shown in above diagram Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); //root->right->left->left = newNode(12); root->right->left->right = newNode(13); root->right->right->left = newNode(14); //root->right->right->right = newNode(15); spiralLevelOrder(root); return 0; }
linear
linear