From f035549e04458aa52b8d4c6843a7b6938a0cd9a6 Mon Sep 17 00:00:00 2001 From: jojoo15 <75017412+jojoo15@users.noreply.github.com> Date: Wed, 19 May 2021 15:40:05 +0200 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200501.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E4=BC=97=E6=95=B0?= =?UTF-8?q?=20python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0501.二叉搜索树中的众数.md | 37 ++++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 385ce2f1..0ddd8b0c 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -394,8 +394,39 @@ class Solution { ``` Python: - - +```python +# 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 not root: return + self.pre = root + self.count = 0 //统计频率 + self.countMax = 0 //最大频率 + self.res = [] + def findNumber(root): + if not root: return None // 第一个节点 + findNumber(root.left) //左 + if self.pre.val == root.val: //中: 与前一个节点数值相同 + self.count += 1 + else: // 与前一个节点数值不同 + self.pre = root + self.count = 1 + if self.count > self.countMax: // 如果计数大于最大值频率 + self.countMax = self.count // 更新最大频率 + self.res = [root.val] //更新res + elif self.count == self.countMax: // 如果和最大值相同,放进res中 + self.res.append(root.val) + findNumber(root.right) //右 + return + findNumber(root) + return self.res +``` Go: @@ -405,4 +436,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -