Skip to content

1305. All Elements in Two Binary Search Trees 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class BSTIterator {
 public:
  BSTIterator(TreeNode* root) {
    pushLeftsUntilNull(root);
  }

  int peek() {
    return stack.top()->val;
  }

  void next() {
    TreeNode* node = stack.top(); stack.pop();
    pushLeftsUntilNull(node->right);
  }

  bool hasNext() {
    return !stack.empty();
  }

 private:
  stack<TreeNode*> stack;

  void pushLeftsUntilNull(TreeNode* node) {
    while (node) {
      stack.push(node);
      node = node->left;
    }
  }
};

class Solution {
 public:
  vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
    vector<int> ans;
    BSTIterator bstIterator1(root1);
    BSTIterator bstIterator2(root2);

    while (bstIterator1.hasNext() && bstIterator2.hasNext())
      if (bstIterator1.peek() < bstIterator2.peek()) {
        ans.push_back(bstIterator1.peek());
        bstIterator1.next();
      } else {
        ans.push_back(bstIterator2.peek());
        bstIterator2.next();
      }

    while (bstIterator1.hasNext()) {
      ans.push_back(bstIterator1.peek());
      bstIterator1.next();
    }

    while (bstIterator2.hasNext()) {
      ans.push_back(bstIterator2.peek());
      bstIterator2.next();
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class BSTIterator {
  public BSTIterator(TreeNode root) {
    pushLeftsUntilNull(root);
  }

  public int peek() {
    return stack.peek().val;
  }

  public void next() {
    pushLeftsUntilNull(stack.pop().right);
  }

  public boolean hasNext() {
    return !stack.isEmpty();
  }

  private Deque<TreeNode> stack = new ArrayDeque<>();

  private void pushLeftsUntilNull(TreeNode node) {
    while (node != null) {
      stack.push(node);
      node = node.left;
    }
  }
}

class Solution {
  public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
    List<Integer> ans = new ArrayList<>();
    BSTIterator bstIterator1 = new BSTIterator(root1);
    BSTIterator bstIterator2 = new BSTIterator(root2);

    while (bstIterator1.hasNext() && bstIterator2.hasNext())
      if (bstIterator1.peek() < bstIterator2.peek()) {
        ans.add(bstIterator1.peek());
        bstIterator1.next();
      } else {
        ans.add(bstIterator2.peek());
        bstIterator2.next();
      }

    while (bstIterator1.hasNext()) {
      ans.add(bstIterator1.peek());
      bstIterator1.next();
    }

    while (bstIterator2.hasNext()) {
      ans.add(bstIterator2.peek());
      bstIterator2.next();
    }

    return ans;
  }
}