From 970a441f1034e7c65881c4867d03de300776589f Mon Sep 17 00:00:00 2001 From: Asterisk <44215173+casnz1601@users.noreply.github.com> Date: Thu, 7 Oct 2021 19:29:26 +0800 Subject: [PATCH] =?UTF-8?q?Update=200501.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E4=BC=97=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 规范Python3代码 --- problems/0501.二叉搜索树中的众数.md | 68 ++++++++++++-------- 1 file changed, 42 insertions(+), 26 deletions(-) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 29e5e139..18d9b290 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -470,38 +470,54 @@ class Solution { ## 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: + def __init__(self): + self.pre = TreeNode() + self.count = 0 + self.max_count = 0 + self.result = [] + 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 + if not root: return None + self.search_BST(root) + return self.result + + def search_BST(self, cur: TreeNode) -> None: + if not cur: return None + self.search_BST(cur.left) + # 第一个节点 + if not self.pre: + self.count = 1 + # 与前一个节点数值相同 + elif self.pre.val == cur.val: + self.count += 1 + # 与前一个节点数值不相同 + else: + self.count = 1 + self.pre = cur + + 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: def findMode(self, root: TreeNode) -> List[int]: stack = []