本题是一个二叉搜索树,遇到二叉搜索树最清楚的是用中序遍历,因为中序遍历直接由小到大排序,然后根据要求修改代码。本题需要找到众数,经过中序遍历后记录排序后的数组的最大众数,直接得到结果,但是代码实现比较麻烦。
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
class Solution {
//最终结果
private int[] res;
//暂时盛放符合的结果
private ArrayList<Integer> list;
//判断当前最大相同数的数量
private int count;
//遍历当前节点的上一个节点,为null说明还没开始遍历
private TreeNode pre;
//记录最大众数数量
private int maxCount;
public int[] findMode(TreeNode root) {
count = 0;
maxCount = 0;
pre = null;
list = new ArrayList<>();
dfs(root);
res = new int[list.size()];
for (int i = 0; i < list.size(); i ++) {
res[i] = list.get(i);
}
return res;
}
private void dfs(TreeNode root) {
if (root == null) return;
dfs(root.left);
int rootValue = root.val;
//当前遍历的是最左边的值或者当前遍历的值和前一个值不相同,那么更新count。
if (pre == null || rootValue != pre.val) {
count = 1;
} else {
//否则说明这两个数相等,那么将count+1;
count++;
}
if (count > maxCount) {
maxCount = count;
list.clear();
list.add(rootValue);
} else if (maxCount == count) {
list.add(rootValue);
}
pre = root;
dfs(root.right);
}
}
迭代法:也是中序遍历,只是用了迭代来实现。
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();
}
}