题目
题目链接:https://leetcode-cn.com/problems/all-elements-in-two-binary-search-trees/
题目解析:这题非常简单,直接通过递归收集数字,然后利用Collections集合的sort方法排序即可。
复杂度分析:
时间复杂度:O(nlogn)因为用到了排序。
空间复杂度:O(n)开辟了一个m+n(跟n同量级)大小的list,m代表tree1的节点数、nn代表tree2的节点数。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;//根值
* TreeNode left;//左子树
* TreeNode right;//右子树
* TreeNode(int x) { val = x; }//构造方法
* }
*/
class Solution {
//创建答案的集合
List<Integer> list = new ArrayList<Integer>();
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
//遍历左子树
go(root1);
//遍历右子树
go(root2);
//将集合排序
Collections.sort(list);
return list;
}
private void go(TreeNode root) {
//当子树为空时返回
if(root==null)
return;
//集合添加根植
list.add(root.val);
//左子树遍历
go(root.left);
//右子树遍历
go(root.right);
}
}