본문 바로가기

Algorithm

501 : Find Mode in Binary Search Tree ( leetcode / java )

반응형

 

*해결 과정

이진탐색 트리라는 것을 친절하게 설명하고 있습니다. 그것보다도, 중복된 요소를 찾고 list로 반환하는 것이 더 중요해보입니다. Integer만을 다루는 Map의 형태이며 중복을 찾아야 하기 때문에 모든 요소 값에 따라서 등장할 때마다 +1씩 하도록 했습니다. 그리고 처음부터 순회하면서 value값이 최대로 큰 경우를 고르고 key값을 list에 넣어서 반환합니다.

 

import java.util.*;
class Solution {
    
    Map<Integer, Integer> map = new HashMap<>();
    
	public int[] findMode(TreeNode root) {
        if(root==null) return new int[]{};
        DFS(root);
        
        int max = Collections.max(map.values());
        List<Integer> ans = new LinkedList<>();
        
        for(Map.Entry<Integer, Integer> m : map.entrySet()) {
        	if(m.getValue()==max) ans.add(m.getKey());
        }
        
        int[] answer = ans.stream().mapToInt(i->i).toArray();
        return answer;
    }

	public void DFS(TreeNode root) {
		map.merge(root.val, 1, Integer::sum);
		if (root.left != null)
			DFS(root.left);
		if (root.right != null)
			DFS(root.right);
	}
}

우리가 Map에서 value의 최댓값을 구할 떄 , Collections.max()를 사용한다는 것

List<Integer>를 int[]로 바꿀 때, stream().mapToInt(i->i)를 사용하면 짧은 코드를 만들 수 있습니다.

(하지만 시간적인 효율을 장담할 수 엇습니다.)

반응형