Leetcode Problem 1305. All Elements in Two Binary Search Trees

1305. All Elements in Two Binary Search Trees

Leetcode Solutions

Iterative Inorder Traversal, One Pass, Linear Time

  1. Initialize two stacks to keep track of the nodes for both trees.
  2. Initialize an empty list to store the merged output.
  3. Perform a loop until both stacks are empty. a. Push all the left children of the current node of both trees onto their respective stacks. b. Compare the top elements of both stacks. c. Pop the smaller element from its stack and add it to the output list. d. Move to the right child of the popped node and continue the process.
  4. Return the merged output list.
UML Thumbnail

Recursive Inorder Traversal + Sort

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...