All Elements in Two Binary Search Trees in C++

C++Server Side ProgrammingProgramming

Suppose we have two binary search trees, we have to return a list of values, that has all elements present in these trees, and the list elements will be in ascending order. So if the trees are like −

Then the output will be [0,1,1,2,3,4].

To solve this, we will follow these steps −

  • Define an array called ans, define two stacks st1 and st2
  • curr1 := root1 and curr2 := root2
  • insert node root1 and all left nodes into st1, insert node root2 and all left nodes into st2
  • while st1 is not empty or st2 is not empty
    • if st1 is not empty, and (st2 is empty or top node value of st1 <= top node value of st2)
      • temp := top of st1, delete node from st1
      • insert value of temp into ans
      • insert node right of temp and all left nodes of it into st1
    • Otherwise −
      • temp := top of st2, delete node from st2
      • insert value of temp into ans
      • insert node right of temp and all left nodes of it into st2
  • return ans

Example

Let us see the following implementation to get better understanding −

class Solution {
public:
   void pushLeft(stack <TreeNode*>& st, TreeNode* root){
      TreeNode* curr = root;
      while(curr){
         st.push(curr);
         curr = curr->left;
      }
   }
   vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
      vector <int> ans;
      stack <TreeNode*> st1, st2;
      TreeNode* curr1 = root1;
      TreeNode* curr2 = root2;
      pushLeft(st1, curr1);
      pushLeft(st2, curr2);
      while(!st1.empty() || !st2.empty()){
         TreeNode* temp;
         if(!st1.empty() && (st2.empty() || st1.top()->val <= st2.top()->val)){
            temp = st1.top();
            st1.pop();
            ans.push_back(temp->val);
            pushLeft(st1, temp->right);
         } else {
            temp = st2.top();
            st2.pop();
            ans.push_back(temp->val);
            pushLeft(st2, temp->right);
         }
      }
      return ans;
   }
};

Input

[2,1,4]
[1,0,3]

Output

[0,1,1,2,3,4]
raja
Published on 18-Mar-2020 05:34:45
Advertisements