tinycodinglm / cp /cp-10010.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
1.92 kB
opencode trace
System You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

User

Problem: Find Mode in Binary Search Tree (Difficulty: Easy)
Tags: Tree, Depth-First Search, Binary Search Tree, Binary Tree

Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.
If the tree has more than one mode, return them in any order.
Assume a BST is defined as follows:

Example 1:
Input: root = [1,null,2,2]
Output: [2]

Example 2:
Input: root = [0]
Output: [0]

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -10^5 <= Node.val <= 10^5
Assistant

Time: O(n)

Space: O(h)

class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def inorder(root, prev, cnt, max_cnt, result):
if not root:
return prev, cnt, max_cnt

markdown
prev, cnt, max_cnt = inorder(root.left, prev, cnt, max_cnt, result)
        if prev:
            if root.val == prev.val:
                cnt += 1
            else:
                cnt = 1
        if cnt > max_cnt:
            max_cnt = cnt
            del result[:]
            result.append(root.val)
        elif cnt == max_cnt:
            result.append(root.val)
        return inorder(root.right, root, cnt, max_cnt, result)

    if not root:
        return []
    result = []
    inorder(root, None, 1, 0, result)
    return result