mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
新增 Java 統一迭代法
新增 Java 統一迭代法
This commit is contained in:
@ -472,6 +472,59 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
統一迭代法
|
||||||
|
```Java
|
||||||
|
class Solution {
|
||||||
|
public int[] findMode(TreeNode root) {
|
||||||
|
int count = 0;
|
||||||
|
int maxCount = 0;
|
||||||
|
TreeNode pre = null;
|
||||||
|
LinkedList<Integer> res = new LinkedList<>();
|
||||||
|
Stack<TreeNode> stack = new Stack<>();
|
||||||
|
|
||||||
|
if(root != null)
|
||||||
|
stack.add(root);
|
||||||
|
|
||||||
|
while(!stack.isEmpty()){
|
||||||
|
TreeNode curr = stack.peek();
|
||||||
|
if(curr != null){
|
||||||
|
stack.pop();
|
||||||
|
if(curr.right != null)
|
||||||
|
stack.add(curr.right);
|
||||||
|
stack.add(curr);
|
||||||
|
stack.add(null);
|
||||||
|
if(curr.left != null)
|
||||||
|
stack.add(curr.left);
|
||||||
|
}else{
|
||||||
|
stack.pop();
|
||||||
|
TreeNode temp = stack.pop();
|
||||||
|
if(pre == null)
|
||||||
|
count = 1;
|
||||||
|
else if(pre != null && pre.val == temp.val)
|
||||||
|
count++;
|
||||||
|
else
|
||||||
|
count = 1;
|
||||||
|
pre = temp;
|
||||||
|
if(count == maxCount)
|
||||||
|
res.add(temp.val);
|
||||||
|
if(count > maxCount){
|
||||||
|
maxCount = count;
|
||||||
|
res.clear();
|
||||||
|
res.add(temp.val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int[] result = new int[res.size()];
|
||||||
|
int i = 0;
|
||||||
|
for (int x : res){
|
||||||
|
result[i] = x;
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
## Python
|
## Python
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user