-
106일 (1305. All Elements in Two Binary Search Trees) recursion, tree지식/알고리즘 2024. 1. 4. 03:53
Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.
Example 1:
Input: root1 = [2,1,4], root2 = [1,0,3] Output: [0,1,1,2,3,4]
Example 2:
Input: root1 = [1,null,8], root2 = [8,1] Output: [1,1,8,8]
Constraints:
- The number of nodes in each tree is in the range [0, 5000].
- -10^5 <= Node.val <= 10^5
- 접근방법
카테고리는 sorting으로 선택하였지만
실상은 전위순회 방식의 재귀함수를 이용한 후 list에 담고, list를 오름차순 정렬한 후 리턴하면 된다.
- 코드
class Solution { public List<Integer> getAllElements(TreeNode root1, TreeNode root2) { ArrayList<Integer> list = new ArrayList<>(); helper(root1, list); helper(root2, list); Collections.sort(list); // 정렬 return list; } public void helper(TreeNode root, ArrayList<Integer> list){ // 전위순회 if(root == null) return; list.add(root.val); helper(root.left,list); helper(root.right,list); } }
재귀호출과 전위, 중위, 후위순회가 무엇인지 복습하는 문제이다.https://leetcode.com/problems/all-elements-in-two-binary-search-trees/
All Elements in Two Binary Search Trees - LeetCode
Can you solve this real interview question? All Elements in Two Binary Search Trees - Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order. Example 1: [https://assets.leetcode
leetcode.com
'지식 > 알고리즘' 카테고리의 다른 글
108일 (1221. Split a String in Balanced Strings) greedy 쉬움 (0) 2024.01.06 107일 (1630. Arithmetic Subarrays) sorting (0) 2024.01.05 105일 (2545. Sort the Students by Their Kth Score) sorting (0) 2024.01.03 104일 (2610. Convert an Array Into a 2D Array With Conditions) sorting (0) 2024.01.02 103일 (2785. Sort Vowels in a String) Sort, pointers (0) 2024.01.01