1305. 两棵二叉搜索树中的所有元素
归并排序
import java.util.ArrayList;
import java.util.List;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
// inorder traversal
void dfs(TreeNode node, List<Integer> list) {
if (node == null) return;
dfs(node.left, list);
list.add(node.val);
dfs(node.right, list);
}
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
List<Integer> list1 = new ArrayList<>(), list2 = new ArrayList<>();
dfs(root1, list1);
dfs(root2, list2);
// merge-sort
int n = list1.size(), m = list2.size();
int i = 0, j = 0;
List<Integer> ans = new ArrayList<>();
while (i < n && j < m) {
if (list1.get(i) <= list2.get(j)) {
ans.add(list1.get(i));
i++;
} else {
ans.add(list2.get(j));
j++;
}
}
while (i < n) {
ans.add(list1.get(i));
i++;
}
while (j < m) {
ans.add(list2.get(j));
j++;
}
return ans;
}
public static void main(String[] args) {
TreeNode a = new TreeNode(2), b = new TreeNode(1), c = new TreeNode(4),
d = new TreeNode(1), e = new TreeNode(0), f = new TreeNode(3);
a.left = b;
a.right = c;
d.left = e;
d.right = f;
System.out.println(new Solution().getAllElements(a, d));
}
}
这个题目中,两棵树都是二叉搜索树,可以先用中序遍历存下两棵数中的值,记为list1, list2, 因为list1和list2都是有序排列的,所以对两个list进行归并排序就可以了。这样是线性复杂度
DFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
merge(root1, list);
merge(root2, list);
Collections.sort(list);
return list;
}
public void merge(TreeNode root, List<Integer> res) {
if (root == null) return;
merge(root.left, res);
list.add(root.val);
merge(root.right, res);
}
}