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

Commit da4116b

Browse files
新增 Java 統一迭代法
新增 Java 統一迭代法
1 parent f979407 commit da4116b

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

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

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,59 @@ class Solution {
472472
}
473473
}
474474
```
475+
統一迭代法
476+
```Java
477+
class Solution {
478+
public int[] findMode(TreeNode root) {
479+
int count = 0;
480+
int maxCount = 0;
481+
TreeNode pre = null;
482+
LinkedList<Integer> res = new LinkedList<>();
483+
Stack<TreeNode> stack = new Stack<>();
484+
485+
if(root != null)
486+
stack.add(root);
487+
488+
while(!stack.isEmpty()){
489+
TreeNode curr = stack.peek();
490+
if(curr != null){
491+
stack.pop();
492+
if(curr.right != null)
493+
stack.add(curr.right);
494+
stack.add(curr);
495+
stack.add(null);
496+
if(curr.left != null)
497+
stack.add(curr.left);
498+
}else{
499+
stack.pop();
500+
TreeNode temp = stack.pop();
501+
if(pre == null)
502+
count = 1;
503+
else if(pre != null && pre.val == temp.val)
504+
count++;
505+
else
506+
count = 1;
507+
pre = temp;
508+
if(count == maxCount)
509+
res.add(temp.val);
510+
if(count > maxCount){
511+
maxCount = count;
512+
res.clear();
513+
res.add(temp.val);
514+
}
515+
}
516+
}
517+
int[] result = new int[res.size()];
518+
int i = 0;
519+
for (int x : res){
520+
result[i] = x;
521+
i++;
522+
}
523+
return result;
524+
}
525+
}
526+
```
527+
475528

476529
## Python
477530

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /