1. 程式人生 > 實用技巧 >[LeetCode] 1305. All Elements in Two Binary Search Trees

[LeetCode] 1305. All Elements in Two Binary Search Trees

Given two binary search treesroot1androot2.

Return a list containingall the integersfromboth treessorted inascendingorder.

Example 1:

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

Example 2:

Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
Output: [-10,0,0,1,2,5,7,10]

Example 3:

Input: root1 = [], root2 = [5,1,7,0,2]
Output: [0,1,2,5,7]

Example 4:

Input: root1 = [0,-10,10], root2 = []
Output: [-10,0,10]

Example 5:

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

Constraints:

  • Each tree has at most5000nodes.
  • Each node's value is between[-10^5, 10^5].

兩棵二叉搜尋樹中的所有元素。題目就是題意,題目給的是兩棵二叉搜尋樹,請你返回的是一個有序的list,裡面包含了來自兩棵樹的所有元素。

這道題的思路就是二叉樹的中序遍歷

94題 + merge two lists 21題。因為input給的是二叉搜尋樹所以最好是用中序遍歷。

時間O(n)

空間O(n)

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> list1 = new ArrayList<>(); 19 inorder(root1, list1); 20 List<Integer> list2 = new ArrayList<>(); 21 inorder(root2, list2); 22 return merge(list1, list2); 23 } 24 25 private void inorder(TreeNode root, List<Integer> list) { 26 if (root == null) { 27 return; 28 } 29 inorder(root.left, list); 30 list.add(root.val); 31 inorder(root.right, list); 32 } 33 34 private List<Integer> merge(List<Integer> list1, List<Integer> list2) { 35 List<Integer> res = new ArrayList<>(); 36 int i = 0; 37 int j = 0; 38 while (i < list1.size() && j < list2.size()) { 39 if (list1.get(i) < list2.get(j)) { 40 res.add(list1.get(i)); 41 i++; 42 } else { 43 res.add(list2.get(j)); 44 j++; 45 } 46 } 47 while (i < list1.size()) { 48 res.add(list1.get(i)); 49 i++; 50 } 51 while (j < list2.size()) { 52 res.add(list2.get(j)); 53 j++; 54 } 55 return res; 56 } 57 }

LeetCode 題目總結