From fba61466482ff32021f9775ee99b96b2a8a73305 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=97=A4=E9=9C=B2?= <080301087@163.com> Date: Mon, 12 Jul 2021 11:35:45 +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=20-?= =?UTF-8?q?=20=E5=A2=9E=E5=8A=A0=E4=BA=86python3=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E7=9A=84=E8=BF=AD=E4=BB=A3=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0501.二叉搜索树中的众数.md | 62 +++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 66be790f..ac7ff603 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -435,7 +435,7 @@ Python: # self.val = val # self.left = left # self.right = right -//递归法 +# 递归法 class Solution: def findMode(self, root: TreeNode) -> List[int]: if not root: return @@ -460,6 +460,66 @@ class Solution: return findNumber(root) return self.res + + +# 迭代法-中序遍历-使用额外空间map的方法: +class Solution: + def findMode(self, root: TreeNode) -> List[int]: + stack = [] + cur = root + pre = None + dist = {} + while cur or stack: + if cur: # 指针来访问节点,访问到最底层 + stack.append(cur) + cur = cur.left + else: # 逐一处理节点 + cur = stack.pop() + if cur.val in dist: + dist[cur.val] += 1 + else: + dist[cur.val] = 1 + pre = cur + cur = cur.right + + # 找出字典中最大的key + res = [] + for key, value in dist.items(): + if (value == max(dist.values())): + res.append(key) + return res + +# 迭代法-中序遍历-不使用额外空间,利用二叉搜索树特性: +class Solution: + def findMode(self, root: TreeNode) -> List[int]: + stack = [] + cur = root + pre = None + maxCount, count = 0, 0 + res = [] + while cur or stack: + if cur: # 指针来访问节点,访问到最底层 + stack.append(cur) + cur = cur.left + else: # 逐一处理节点 + cur = stack.pop() + if pre == None: # 第一个节点 + count = 1 + elif pre.val == cur.val: # 与前一个节点数值相同 + count += 1 + else: + count = 1 + if count == maxCount: + res.append(cur.val) + if count > maxCount: + maxCount = count + res.clear() + res.append(cur.val) + + pre = cur + cur = cur.right + return res + ``` Go: 暴力法(非BSL)