1. 程式人生 > >501. Find Mode in Binary Search Tree查找BST中的眾數

501. Find Mode in Binary Search Tree查找BST中的眾數

pan 為什麽 AR dup 不用 lan 結果 with bug

[抄題]:

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

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.

For example:
Given BST [1,null,2,2],

   1
         2
    /
   2

return [2].

[暴力解法]:

時間分析:

空間分析:hashmap:n

[優化後]:

時間分析:

空間分析:各種count

[奇葩輸出條件]:

返回具體元素,不是次數。所以過來 nums[次數] = 元素。

[奇葩corner case]:

[思維問題]:

新建數組指定空間,多大不知道,所以需要提前遍歷一下

[一句話思路]:

先存maxcount,符合要求之後再存modecount

[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):

[畫圖]:

[一刷]:

  1. 返回值的單個函數中,必須把全局變量再寫一遍
  2. 處理的情況寫if, else if,不處理的不用管
  3. inorder遍歷本質是dfs,也有退出條件

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分鐘肉眼debug的結果]:

[總結]:

[復雜度]:Time complexity: O() Space complexity: O()

[英文數據結構或算法,為什麽不用別的數據結構或算法]:

[關鍵模板化代碼]:

[其他解法]:

[Follow Up]:

[LC給出的題目變變變]:

[代碼風格] :

501. Find Mode in Binary Search Tree查找BST中的眾數