Posts

Showing posts with the label Amazon

Traverse by Zig-Zag order

/*** zig-zag traversal of a binary tree. ***/ #include <iostream> #include <stack> #include <vector> using namespace std; struct node{        int val;        node *left, *right; }; void zigzag(stack<node*> pre, vector<node*> *v, int flag) {        if (pre.empty()) return ;        stack<node *> cur;        while (!pre.empty()) {               node *n = pre.top();               pre.pop();               v->push_back(n);               if (flag%2 == 0) {                ...

Prune Tree

/*** amazon, tree related problem In a binary tree, a complete path is defined as a path from root to a leaf. The sum of all nodes on that path is defined as the sum of that path. Given a number K, we have to remove (prune the tree) nodes from the tree which lie on a path having sum less than K. A node can be part of multiple paths. So we have to delete it only in case when all paths from it have sum less than K. ***/ #include <iostream> using namespace std; #define K 5 struct node {        int val;        node *left, *right; }; bool remove_node(node *n, int left, int right) {        if (n->left == nullptr && n->right == nullptr )        {               return false ;        }        if (left) {    ...

Check String Chaining

/*** You are given an array of Strings, return TRUE if and only if All the strings can be connected in one chain. Condition for connectivity is , if the last character of one string matches first character of second string, the two string can be connected. Example : String []arr ={"abc", "cde", "cad" , "def" , "eac"} will return TRUE coz all strings can be connected in one chain "abc"->"cde"->"eac"->"cad"->"def" Another Example : String []arr ={"acb" , "cde", "def", "ead" } returns False coz "cde"->"ead"->"def" is the possible chain but “acb” is left out. Note : Its not necessary to start with the first String and form the chain, It may happen that you won’t get a chain if you start with first string but you can get a chain if you Start with any other String. If there exists a possible...

Big Difference

/*** There is an integer array consisting positive and negative integers. Find maximum positive difference S defined as: S = a[i] - a[j] where i>j and S > 0 ***/ #include <iostream> using namespace std; int bigDiff( int * a , int sz ) {        int min = 0;        int dif = 0;        for ( int i = 0; i< sz ; i++) {               if ( a [i] < 0)               {                      if (min > a [i]) min = a [i];               } else {                  ...