Skip to content

Commit 7625216

Browse files
Merge pull request youngyangyang04#490 from Miraclelucy/master
Update 0501.二叉搜索树中的众数.md - 增加了python3版本的迭代解法
2 parents bf9469e + fba6146 commit 7625216

File tree

1 file changed

+61
-1
lines changed

1 file changed

+61
-1
lines changed

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

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -435,7 +435,7 @@ Python:
435435
# self.val = val
436436
# self.left = left
437437
# self.right = right
438-
//递归法
438+
# 递归法
439439
class Solution:
440440
def findMode(self, root: TreeNode) -> List[int]:
441441
if not root: return
@@ -460,6 +460,66 @@ class Solution:
460460
return
461461
findNumber(root)
462462
return self.res
463+
464+
465+
# 迭代法-中序遍历-使用额外空间map的方法:
466+
class Solution:
467+
def findMode(self, root: TreeNode) -> List[int]:
468+
stack = []
469+
cur = root
470+
pre = None
471+
dist = {}
472+
while cur or stack:
473+
if cur: # 指针来访问节点,访问到最底层
474+
stack.append(cur)
475+
cur = cur.left
476+
else: # 逐一处理节点
477+
cur = stack.pop()
478+
if cur.val in dist:
479+
dist[cur.val] += 1
480+
else:
481+
dist[cur.val] = 1
482+
pre = cur
483+
cur = cur.right
484+
485+
# 找出字典中最大的key
486+
res = []
487+
for key, value in dist.items():
488+
if (value == max(dist.values())):
489+
res.append(key)
490+
return res
491+
492+
# 迭代法-中序遍历-不使用额外空间,利用二叉搜索树特性:
493+
class Solution:
494+
def findMode(self, root: TreeNode) -> List[int]:
495+
stack = []
496+
cur = root
497+
pre = None
498+
maxCount, count = 0, 0
499+
res = []
500+
while cur or stack:
501+
if cur: # 指针来访问节点,访问到最底层
502+
stack.append(cur)
503+
cur = cur.left
504+
else: # 逐一处理节点
505+
cur = stack.pop()
506+
if pre == None: # 第一个节点
507+
count = 1
508+
elif pre.val == cur.val: # 与前一个节点数值相同
509+
count += 1
510+
else:
511+
count = 1
512+
if count == maxCount:
513+
res.append(cur.val)
514+
if count > maxCount:
515+
maxCount = count
516+
res.clear()
517+
res.append(cur.val)
518+
519+
pre = cur
520+
cur = cur.right
521+
return res
522+
463523
```
464524
Go:
465525
暴力法(非BSL)

0 commit comments

Comments
 (0)