Leetcode之兩棵二叉搜尋樹中的所有元素
阿新 • • 發佈:2020-10-05
問題描述
給你 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]
問題解法
中序遍歷+合併排序
這是一開始的想法。
/** * 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; } }
執行時間比上面合併排序要快