File tree Expand file tree Collapse file tree 1 file changed +61
-1
lines changed Expand file tree Collapse file tree 1 file changed +61
-1
lines changed Original file line number Diff line number Diff line change @@ -435,7 +435,7 @@ Python:
435
435
# self.val = val
436
436
# self.left = left
437
437
# self.right = right
438
- // 递归法
438
+ # 递归法
439
439
class Solution :
440
440
def findMode (self , root : TreeNode) -> List[int ]:
441
441
if not root: return
@@ -460,6 +460,66 @@ class Solution:
460
460
return
461
461
findNumber(root)
462
462
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
+
463
523
```
464
524
Go:
465
525
暴力法(非BSL)
You can’t perform that action at this time.
0 commit comments