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