LeetCode 1305. All Elements in Two Binary Search Trees

原题链接在这里:https://leetcode.com/problems/all-elements-in-two-binary-search-trees/description/

题目:

Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.

Example 1:

Input: root1 = [2,1,4], root2 = [1,0,3]
Output: [0,1,1,2,3,4]

Example 2:

Input: root1 = [1,null,8], root2 = [8,1]
Output: [1,1,8,8]

Constraints:

  • The number of nodes in each tree is in the range [0, 5000].
  • -105 <= Node.val <= 105

题解:

It is like to use the iterator of binary search tree. Thus use stk to stimulate the iterator.

If both stacks are not empty, compare the top and pop the smaller one, and update the corresponding stack.

Time Complexity: O(n1 + n2). n1 is num of nodes in the first tree. n2 is number of node in the second tree.

Space: O(h1 + h2). h1 is the height of the first tree. h2 is height of the second tree.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
18         List<Integer> res = new ArrayList<>();
19         Stack<TreeNode> stk1 = new Stack<>();
20         Stack<TreeNode> stk2 = new Stack<>();
21         pushLeft(stk1, root1);
22         pushLeft(stk2, root2);
23         
24         while(!stk1.isEmpty() && !stk2.isEmpty()){
25             if(stk1.peek().val < stk2.peek().val){
26                 TreeNode cur = stk1.pop();
27                 res.add(cur.val);
28                 pushLeft(stk1, cur.right);
29             }else{
30                 TreeNode cur = stk2.pop();
31                 res.add(cur.val);
32                 pushLeft(stk2, cur.right);
33             }
34         }
35         
36         while(!stk1.isEmpty()){
37             TreeNode cur = stk1.pop();
38             res.add(cur.val);
39             pushLeft(stk1, cur.right);
40         }
41         
42         while(!stk2.isEmpty()){
43             TreeNode cur = stk2.pop();
44             res.add(cur.val);
45             pushLeft(stk2, cur.right);
46         }
47         
48         return res;
49     }
50     
51     private void pushLeft(Stack<TreeNode> stk, TreeNode root){
52         while(root != null){
53             stk.push(root);
54             root = root.left;
55         }
56     }
57 }

类似Binary Search Tree Iterator.

posted @ 2024-06-01 13:11  Dylan_Java_NYC  阅读(5)  评论(0编辑  收藏  举报