Leetcode之两棵二叉搜索树中的所有元素
问题描述#
给你 root1 和 root2 这两棵二叉搜索树。
请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。
示例 1:
输入:root1 = [2,1,4], root2 = [1,0,3]
输出:[0,1,1,2,3,4]
示例 2:
输入:root1 = [0,-10,10], root2 = [5,1,7,0,2]
输出:[-10,0,0,1,2,5,7,10]
示例 3:
输入:root1 = [], root2 = [5,1,7,0,2]
输出:[0,1,2,5,7]
示例 4:
输入:root1 = [0,-10,10], root2 = []
输出:[-10,0,10]
输入:root1 = [1,null,8], root2 = [8,1]
输出:[1,1,8,8]
问题解法#
中序遍历+合并排序#
这是一开始的想法。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
List<Integer> list1 =new ArrayList<Integer>();
List<Integer> list2 =new ArrayList<Integer>();
List<Integer> list =new ArrayList<Integer>();
list1=minsearch(root1, list1);
list2=minsearch(root2, list2);
int i=0,j=0;
for(;i<list1.size()&&j<list2.size();) {
if(list1.get(i)<list2.get(j)) {
list.add(list1.get(i));
i++;
}else {
list.add(list2.get(j));
j++;
}
}
if(i>=list1.size()) {
for(;j<list2.size();j++) {
list.add(list2.get(j));
}
}
if(j>=list2.size()) {
for(;i<list1.size();i++) {
list.add(list1.get(i));
}
}
return list;
}
public List<Integer> minsearch(TreeNode q,List<Integer> listp) {
if(q==null)
return listp;
minsearch(q.left,listp);
listp.add(q.val);
minsearch(q.right,listp);
return listp;
}
}
中序遍历到一个集合后,使用Collections来排序#
**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
List<Integer> list1 =new ArrayList<Integer>();
list1=minsearch(root1, list1);
list1=minsearch(root2, list1);
Collections.sort(list1);
return list1;
}
public List<Integer> minsearch(TreeNode q,List<Integer> listp) {
if(q==null)
return listp;
minsearch(q.left,listp);
listp.add(q.val);
minsearch(q.right,listp);
return listp;
}
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 想让你多爱自己一些的开源计时器
· Cursor预测程序员行业倒计时:CTO应做好50%裁员计划
· 大模型 Token 究竟是啥:图解大模型Token
· 如何在 .NET 中 使用 ANTLR4
· 用99元买的服务器搭一套CI/CD系统