All Elements in Two Binary Search Trees LeetCode solution in Java
1class Solution {2public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {3Stack<TreeNode> st1 = new Stack<>();4Stack<TreeNode> st2 = new Stack<>();56List<Integer> res = new ArrayList<>();78while (root1 != null || root2 != null || !st1.empty() || !st2.empty()) {9while (root1 != null) {10st1.push(root1);11root1 = root1.left;12}13while (root2 != null) {14st2.push(root2);15root2 = root2.left;16}17if (st2.empty() || (!st1.empty() && st1.peek().val <= st2.peek().val)) {18root1 = st1.pop();19res.add(root1.val);20root1 = root1.right;21} else {22root2 = st2.pop();23res.add(root2.val);24root2 = root2.right;25}26}27return res;28}29}