mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0501.二叉搜索树中的众数.md
规范Python3代码
This commit is contained in:
@ -470,38 +470,54 @@ class Solution {
|
|||||||
|
|
||||||
## Python
|
## Python
|
||||||
|
|
||||||
递归法
|
> 递归法
|
||||||
|
|
||||||
```python
|
```python3
|
||||||
|
# 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:
|
class Solution:
|
||||||
|
def __init__(self):
|
||||||
|
self.pre = TreeNode()
|
||||||
|
self.count = 0
|
||||||
|
self.max_count = 0
|
||||||
|
self.result = []
|
||||||
|
|
||||||
def findMode(self, root: TreeNode) -> List[int]:
|
def findMode(self, root: TreeNode) -> List[int]:
|
||||||
if not root: return
|
if not root: return None
|
||||||
self.pre = root
|
self.search_BST(root)
|
||||||
self.count = 0 //统计频率
|
return self.result
|
||||||
self.countMax = 0 //最大频率
|
|
||||||
self.res = []
|
def search_BST(self, cur: TreeNode) -> None:
|
||||||
def findNumber(root):
|
if not cur: return None
|
||||||
if not root: return None // 第一个节点
|
self.search_BST(cur.left)
|
||||||
findNumber(root.left) //左
|
# 第一个节点
|
||||||
if self.pre.val == root.val: //中: 与前一个节点数值相同
|
if not self.pre:
|
||||||
self.count += 1
|
|
||||||
else: // 与前一个节点数值不同
|
|
||||||
self.pre = root
|
|
||||||
self.count = 1
|
self.count = 1
|
||||||
if self.count > self.countMax: // 如果计数大于最大值频率
|
# 与前一个节点数值相同
|
||||||
self.countMax = self.count // 更新最大频率
|
elif self.pre.val == cur.val:
|
||||||
self.res = [root.val] //更新res
|
self.count += 1
|
||||||
elif self.count == self.countMax: // 如果和最大值相同,放进res中
|
# 与前一个节点数值不相同
|
||||||
self.res.append(root.val)
|
else:
|
||||||
findNumber(root.right) //右
|
self.count = 1
|
||||||
return
|
self.pre = cur
|
||||||
findNumber(root)
|
|
||||||
return self.res
|
if self.count == self.max_count:
|
||||||
|
self.result.append(cur.val)
|
||||||
|
|
||||||
|
if self.count > self.max_count:
|
||||||
|
self.max_count = self.count
|
||||||
|
self.result = [cur.val] # 清空self.result,确保result之前的的元素都失效
|
||||||
|
|
||||||
|
self.search_BST(cur.right)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
迭代法-中序遍历-不使用额外空间,利用二叉搜索树特性
|
> 迭代法-中序遍历-不使用额外空间,利用二叉搜索树特性
|
||||||
```python
|
```python3
|
||||||
class Solution:
|
class Solution:
|
||||||
def findMode(self, root: TreeNode) -> List[int]:
|
def findMode(self, root: TreeNode) -> List[int]:
|
||||||
stack = []
|
stack = []
|
||||||
|
Reference in New Issue
Block a user