# Leetcode 1305. All Elements in Two Binary Search Trees ###### tags: `Leetcode(JAVA)` 題目 : https://leetcode.com/problems/all-elements-in-two-binary-search-trees/ 。 想法 : 先走訪再排序。 時間複雜度 : O(nlogn)。 程式碼 : (JAVA) ``` /** * 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 { List<Integer> ans = new ArrayList<Integer>(); void travel(TreeNode root){ if(root == null) return; else{ ans.add(root.val); travel(root.left); travel(root.right); } } public List<Integer> getAllElements(TreeNode root1, TreeNode root2) { travel(root1); travel(root2); int l = ans.size(); Collections.sort(ans); return ans; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up