LeetCode 1305 两棵二叉搜索树中的所有元素(java版)

给你 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]
示例 5:

在这里插入图片描述

输入:root1 = [1,null,8], root2 = [8,1]
输出:[1,1,8,8]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-elements-in-two-binary-search-trees

解题思路:输入的两个树是搜索二叉树(BST),中序遍历得到的数据就是有序的,两个有序的list进行排序最好的方法就是归并排序;当然还可以把两个树无脑的放到list里,使用Collections.sort(list)进行排序,时间复杂度为O(nlogn),没有前者的算法好。

代码:

/**
 * 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>();
	    	getOneList(root1,list1);
	    	getOneList(root2,list2);
	    	List<Integer> listTotal = new ArrayList<Integer>();
	    	int index1,index2;
	    	int size1 = list1.size();
	    	int size2 = list2.size();
	    	for (index1 = 0,index2=0; index1 < size1 && index2 < size2;) {
	    		Integer int1 = list1.get(index1);
	    		Integer int2 = list2.get(index2);
	    		if(int1>int2){
	    			listTotal.add(int2);
	    			index2++;
	    		}else{
	    			listTotal.add(int1);
	    			index1++;
	    		}
			}
	    	while(index1 < size1){
	    		listTotal.add(list1.get(index1++));
	    	}
	    	while(index2 < size2){
	    		listTotal.add(list2.get(index2++));
	    	}
	        return listTotal;
	    }
	    
	    public void getOneList(TreeNode root,List<Integer> list){
	    	if(root == null){
	    		return;
	    	}
	    	getOneList(root.left,list);
	    	list.add(root.val);
	    	getOneList(root.right,list);
	    }
}

结果:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值