본문 바로가기
Computer Science/알고리즘

leetcode 1305) All Elements in Two Binary Search Trees

by eeeun:) 2022. 1. 26.
반응형

LV. Medium 🧐

https://leetcode.com/problems/all-elements-in-two-binary-search-trees/

 

All Elements in Two Binary Search Trees - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

문제

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

 

문제 해결법

vector<int> ans에 노드 1, 노드 2를 다 돌며 val 값을 저장한다.

그 후 sort를 하고 return 하면 끝!

 

해결 코드
class Solution {
private:
	vector<int> ans;
public:
	vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
		set_ans(root1);
		set_ans(root2);
		sort(ans.begin(), ans.end());
		return ans;
	}
	void set_ans(TreeNode* root) {
		if (!root)
			return ;
		ans.push_back(root->val);
		set_ans(root->left);
		set_ans(root->right);
	}
};

 

728x90

'Computer Science > 알고리즘' 카테고리의 다른 글

leetcode 121) Best Time to Buy and Sell Stock  (0) 2022.02.01
leetcode 189) Rotate Array  (0) 2022.01.30
leetcode 1510) Stone Game IV  (0) 2022.01.25
leetcode 941) Valid Mountain Array  (0) 2022.01.25
leetcode 1291) Sequential Digits  (0) 2022.01.25

댓글