動機

BST的inorder就是sort過的list!! 忘了!!

Problem

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:

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

 

Example 1:

Input: root = [1,Leetcode,2,2]Output: [2]

Example 2:

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

 

Constraints:

    t
  • The number of nodes in the tree is in the range [1, 104].
  • t
  • -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).

Sol

dict統計

class Solution:
    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        cnt = defaultdict(int)
        
        def dfs(r):
            if not r:
                return
            else:
                cnt[r.val] += 1
                [dfs(x) for x in [r.left, r.right]]
        
        dfs(root)
        mode = max(cnt.values())
        return [k for (k,v) in cnt.items() if v == mode]

利用inorder就是sort的特性去更新最大值

class Solution:
    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        ret = []
        maxCount = 0
        curCount = 1
        prevNum = None
        def inorder(r):
            nonlocal maxCount, curCount, prevNum, ret
            if not r:
                return
            else:
                inorder(r.left)
                if prevNum == r.val:
                    curCount += 1
                else:
                    curCount = 1
                
                if curCount == maxCount:
                    ret.append(r.val)
                elif curCount > maxCount:
                    maxCount = curCount
                    ret = [r.val]
                prevNum = r.val
                inorder(r.right)
                
        inorder(root)
        return ret