中序遍历
/**
* 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 {
int max = 0;
int count = 0;
TreeNode pre = null;
ArrayList<Integer> array = new ArrayList<Integer>();
public int[] findMode(TreeNode root) {
traversal(root);
// 把ArrayList转为int[]
int[] result = new int[array.size()];
for (int i = 0; i < array.size(); i++) {
result[i] = array.get(i);
}
return result;
}
// 中序遍历
public void traversal(TreeNode root){
if(root == null){
return ;
}
// 左
traversal(root.left);
// 中
if(pre == null){
count = 1;
}else if(pre.val == root.val){
count++;
}else{
count = 1;
}
pre = root;
if(count == max){
array.add(root.val);
}
if(count > max){
max = count;
// ArrayList中清空数组函数clear()
array.clear();
array.add(root.val);
}
// 右
traversal(root.right);
}
}
由于二叉搜索树中序遍历是升序的特性,所以当看到题目中是二叉搜索树时,首先可以想用中序遍历来解决。