Skip to main content

1305 All Elements in Two Binary Search Trees

Leetcode

Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.

先通过前序遍历把树转换为链表,然后合并链表。不确定这样做是最好的方法,可能还有更优的解法。

/**
* 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 {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
LinkedList<Integer> l1 = new LinkedList<>();
LinkedList<Integer> l2 = new LinkedList<>();

if(root1 != null) preOrder(root1, l1);
if(root2 != null) preOrder(root2, l2);

List<Integer> ret = new LinkedList<>();

while(l1.size()>0 && l2.size()>0){
if(l1.peek()<l2.peek()){
ret.add(l1.pop());
} else {
ret.add(l2.pop());
}
}

if(l1.size()>0){
ret.addAll(l1);
} else {
ret.addAll(l2);
}

return ret;
}

private void preOrder(TreeNode node, List<Integer> list){
if(node.left!=null){
preOrder(node.left, list);
}
list.add(node.val);
if(node.right!=null){
preOrder(node.right, list);
}
}


}