import java.util.ArrayList;
import java.util.Stack;
class Solution {
// 迭代法 中序遍历的方式
public int[] findMode(TreeNode root) {
TreeNode pre = null; // 初始值
Stack<TreeNode> stack = new Stack<>();
ArrayList<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;
}
}
// 将ArrayList<Integer> result中的数据存储到int[] res中
Object[] arr = result.toArray();
int[] res = new int[arr.length];
for(int i = 0;i < arr.length;i++){
res[i] = (int) arr[i];
}
return res;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
11-08
291