Skip to content

501. Find Mode in Binary Search 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:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

 

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].
  • -105 <= Node.val <= 105

 

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
Related Topics
  • 深度优先搜索
  • 二叉搜索树
  • 二叉树

  • 👍 805
  • 👎 0
  • 思路

    BST 的中序列遍历 + pre 指针更新操作

    解法

    py
    # leetcode submit region begin(Prohibit modification and deletion)
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def findMode(self, root: Optional[TreeNode]) -> List[int]:
            res = []
            count = 0
            max_count = 0
            pre = None
    
            def dfs(node: Optional[TreeNode]):
                if not node:
                    return
    
                dfs(node.left)
                nonlocal count, pre, max_count, res
    
                if pre is None or pre == node.val:
                    count += 1
                else:
                    count = 1
    
                if count > max_count:
                    res = [node.val]
                    max_count = count
                elif count == max_count:
                    res.append(node.val)
    
                pre = node.val
    
                dfs(node.right)
    
            dfs(root)
            return res
            
    # leetcode submit region end(Prohibit modification and deletion)

    复杂度分析

    • 时间复杂度 O(N)
    • 空间复杂度 O(N)