Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit7625216

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

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
classSolution:
440440
deffindMode(self,root: TreeNode) -> List[int]:
441441
ifnot root:return
@@ -460,6 +460,66 @@ class Solution:
460460
return
461461
findNumber(root)
462462
returnself.res
463+
464+
465+
# 迭代法-中序遍历-使用额外空间map的方法:
466+
classSolution:
467+
deffindMode(self,root: TreeNode) -> List[int]:
468+
stack= []
469+
cur= root
470+
pre=None
471+
dist= {}
472+
while curor stack:
473+
if cur:# 指针来访问节点,访问到最底层
474+
stack.append(cur)
475+
cur= cur.left
476+
else:# 逐一处理节点
477+
cur= stack.pop()
478+
if cur.valin 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, valuein dist.items():
488+
if (value==max(dist.values())):
489+
res.append(key)
490+
return res
491+
492+
# 迭代法-中序遍历-不使用额外空间,利用二叉搜索树特性:
493+
classSolution:
494+
deffindMode(self,root: TreeNode) -> List[int]:
495+
stack= []
496+
cur= root
497+
pre=None
498+
maxCount, count=0,0
499+
res= []
500+
while curor 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)

[8]ページ先頭

©2009-2025 Movatter.jp