파비의 매일매일 공부기록

2023.11.02 Today's Challenge 본문

Problem Solving/LeetCode

2023.11.02 Today's Challenge

fabichoi 2023. 11. 2. 23:45

https://leetcode.com/problems/find-mode-in-binary-search-tree/

 

Find Mode in Binary Search Tree - LeetCode

Can you solve this real interview question? Find Mode in Binary Search Tree - Given the root of a binary search tree (BST) with duplicates, return all the mode(s) [https://en.wikipedia.org/wiki/Mode_(statistics)] (i.e., the most frequently occurred element

leetcode.com

DFS로 푸는 문제.
DFS에도 종류가 좀 있구만..

    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        def dfs(node, counter):
            if not node:
                return
            
            counter[node.val] += 1
            dfs(node.left, counter)
            dfs(node.right, counter)

        counter = defaultdict(int)
        dfs(root, counter)
        max_freq = max(counter.values())

        ans = []

        for key in counter:
            if counter[key] == max_freq:
                ans.append(key)
        
        return ans
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.11.04 Today's Challenge  (0) 2023.11.04
2023.11.03 Today's Challenge  (0) 2023.11.03
2023.11.01 Today's Challenge  (0) 2023.11.01
2023.10.31 Today's Challenge  (0) 2023.10.31
2023.10.30 Today's Challenge  (0) 2023.10.30
Comments