力扣 LeetCode 501. 二叉搜索树中的众数(Day10:二叉树)
解题思路:
中序遍历
很好的技巧
只需遍历一遍就可以获得结果,maxCount实时更新,找到更大的maxCount就会清空原有数组并添加当前元素
class Solution {
List<Integer> list = new ArrayList<>();
TreeNode pre = null;
int cnt = 0;
int maxCnt = 0;
public int[] findMode(TreeNode root) {
traversal(root);
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
public void traversal(TreeNode cur) {
if (cur == null) return;
traversal(cur.left);
if (pre == null || pre.val != cur.val) cnt = 1;
else if (pre.val == cur.val) cnt++;
if (cnt > maxCnt) {
maxCnt = cnt;
list.clear();
list.add(cur.val);
} else if (cnt == maxCnt) {
list.add(cur.val);
}
pre = cur;
traversal(cur.right);
}
}