74. Leetcode 501. 二叉搜索树中的众数 (二叉搜索树-中序遍历类)
生活随笔
收集整理的這篇文章主要介紹了
74. Leetcode 501. 二叉搜索树中的众数 (二叉搜索树-中序遍历类)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你一個含重復值的二叉搜索樹(BST)的根節點 root ,找出并返回 BST 中的所有 眾數(即,出現頻率最高的元素)。如果樹中有不止一個眾數,可以按 任意順序 返回。假定 BST 滿足如下定義:結點左子樹中所含節點的值 小于等于 當前節點的值
結點右子樹中所含節點的值 大于等于 當前節點的值
左子樹和右子樹都是二叉搜索樹示例 1:輸入:root = [1,null,2,2]
輸出:[2]
示例 2:輸入:root = [0]
輸出:[0]# 方法一 層序遍歷 + 字典用層次遍歷,然后用一個字典記錄每個值出現的次數,最后在字典中搜索最大值(即出現次數最多的值,也就是眾數)。
但是這種方法用了額外的空間。# 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: TreeNode) -> List[int]:if root == None:return Nonedicts = {}queue = [root]while queue:length = len(queue)for _ in range(length):node = queue.pop(0)if node.val in dicts:dicts[node.val] += 1else:dicts[node.val] = 1if node.left != None:queue.append(node.left)if node.right != None:queue.append(node.right)# 計算眾數max_num = 0for i,counts in dicts.items():if counts > max_num:res = [i]max_num = countselif counts == max_num:res.append(i)return res方法二: 中序遍歷二叉搜索樹的中序遍歷是一個升序序列,逐個比對當前結點值 cur_node.val與前驅結點值 pre_node.val。更新當前節點值出現次數curTimes及最大出現次數 maxTimes,更新規則:若 curTimes=maxTimes,將cur_node.val添加到結果res中若 curTimes>maxTimes,清空 res,將 cur_node.val 添加到 res,并更新 maxTimes 為 curTimes
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀
總結
以上是生活随笔為你收集整理的74. Leetcode 501. 二叉搜索树中的众数 (二叉搜索树-中序遍历类)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 73. Leetcode 230. 二叉
- 下一篇: 76. Leetcode 295. 数据