Skip to content

Commit f035549

Browse files
authored
添加 0501.二叉搜索树中的众数 python版本
1 parent 786137d commit f035549

File tree

1 file changed

+34
-3
lines changed

1 file changed

+34
-3
lines changed

problems/0501.二叉搜索树中的众数.md

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -394,8 +394,39 @@ class Solution {
394394
```
395395
396396
Python:
397-
398-
397+
```python
398+
# Definition for a binary tree node.
399+
# class TreeNode:
400+
# def __init__(self, val=0, left=None, right=None):
401+
# self.val = val
402+
# self.left = left
403+
# self.right = right
404+
//递归法
405+
class Solution:
406+
def findMode(self, root: TreeNode) -> List[int]:
407+
if not root: return
408+
self.pre = root
409+
self.count = 0 //统计频率
410+
self.countMax = 0 //最大频率
411+
self.res = []
412+
def findNumber(root):
413+
if not root: return None // 第一个节点
414+
findNumber(root.left) //左
415+
if self.pre.val == root.val: //中: 与前一个节点数值相同
416+
self.count += 1
417+
else: // 与前一个节点数值不同
418+
self.pre = root
419+
self.count = 1
420+
if self.count > self.countMax: // 如果计数大于最大值频率
421+
self.countMax = self.count // 更新最大频率
422+
self.res = [root.val] //更新res
423+
elif self.count == self.countMax: // 如果和最大值相同,放进res中
424+
self.res.append(root.val)
425+
findNumber(root.right) //右
426+
return
427+
findNumber(root)
428+
return self.res
429+
```
399430
Go:
400431

401432

@@ -405,4 +436,4 @@ Go:
405436
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
406437
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
407438
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
408-
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
439+
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

0 commit comments

Comments
 (0)