mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加0501.二叉搜索树中的众数.md迭代Java解法
This commit is contained in:
@ -429,6 +429,44 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
迭代法
|
||||||
|
```java
|
||||||
|
class Solution {
|
||||||
|
public int[] findMode(TreeNode root) {
|
||||||
|
TreeNode pre = null;
|
||||||
|
Stack<TreeNode> stack = new Stack<>();
|
||||||
|
List<Integer> result = new ArrayList<>();
|
||||||
|
int maxCount = 0;
|
||||||
|
int count = 0;
|
||||||
|
TreeNode cur = root;
|
||||||
|
while (cur != null || !stack.isEmpty()) {
|
||||||
|
if (cur != null) {
|
||||||
|
stack.push(cur);
|
||||||
|
cur =cur.left;
|
||||||
|
}else {
|
||||||
|
cur = stack.pop();
|
||||||
|
// 计数
|
||||||
|
if (pre == null || cur.val != pre.val) {
|
||||||
|
count = 1;
|
||||||
|
}else {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
// 更新结果
|
||||||
|
if (count > maxCount) {
|
||||||
|
maxCount = count;
|
||||||
|
result.clear();
|
||||||
|
result.add(cur.val);
|
||||||
|
}else if (count == maxCount) {
|
||||||
|
result.add(cur.val);
|
||||||
|
}
|
||||||
|
pre = cur;
|
||||||
|
cur = cur.right;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result.stream().mapToInt(Integer::intValue).toArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Python
|
## Python
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user