Skip to content

Commit 970a441

Browse files
authored
Update 0501.二叉搜索树中的众数.md
规范Python3代码
1 parent 8c27a2a commit 970a441

File tree

1 file changed

+43
-27
lines changed

1 file changed

+43
-27
lines changed

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

Lines changed: 43 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -470,38 +470,54 @@ class Solution {
470470

471471
## Python
472472

473-
递归法
474-
475-
```python
473+
> 递归法
474+
475+
```python3
476+
# Definition for a binary tree node.
477+
# class TreeNode:
478+
# def __init__(self, val=0, left=None, right=None):
479+
# self.val = val
480+
# self.left = left
481+
# self.right = right
476482
class Solution:
483+
def __init__(self):
484+
self.pre = TreeNode()
485+
self.count = 0
486+
self.max_count = 0
487+
self.result = []
488+
477489
def findMode(self, root: TreeNode) -> List[int]:
478-
if not root: return
479-
self.pre = root
480-
self.count = 0 //统计频率
481-
self.countMax = 0 //最大频率
482-
self.res = []
483-
def findNumber(root):
484-
if not root: return None // 第一个节点
485-
findNumber(root.left) //
486-
if self.pre.val == root.val: //中: 与前一个节点数值相同
487-
self.count += 1
488-
else: // 与前一个节点数值不同
489-
self.pre = root
490-
self.count = 1
491-
if self.count > self.countMax: // 如果计数大于最大值频率
492-
self.countMax = self.count // 更新最大频率
493-
self.res = [root.val] //更新res
494-
elif self.count == self.countMax: // 如果和最大值相同,放进res中
495-
self.res.append(root.val)
496-
findNumber(root.right) //
497-
return
498-
findNumber(root)
499-
return self.res
490+
if not root: return None
491+
self.search_BST(root)
492+
return self.result
493+
494+
def search_BST(self, cur: TreeNode) -> None:
495+
if not cur: return None
496+
self.search_BST(cur.left)
497+
# 第一个节点
498+
if not self.pre:
499+
self.count = 1
500+
# 与前一个节点数值相同
501+
elif self.pre.val == cur.val:
502+
self.count += 1
503+
# 与前一个节点数值不相同
504+
else:
505+
self.count = 1
506+
self.pre = cur
507+
508+
if self.count == self.max_count:
509+
self.result.append(cur.val)
510+
511+
if self.count > self.max_count:
512+
self.max_count = self.count
513+
self.result = [cur.val] # 清空self.result,确保result之前的的元素都失效
514+
515+
self.search_BST(cur.right)
500516
```
501517

502518

503-
迭代法-中序遍历-不使用额外空间,利用二叉搜索树特性
504-
```python
519+
> 迭代法-中序遍历-不使用额外空间,利用二叉搜索树特性
520+
```python3
505521
class Solution:
506522
def findMode(self, root: TreeNode) -> List[int]:
507523
stack = []

0 commit comments

Comments
 (0)