截止到目前我已经写了 500多道算法题,其中部分已经整理成了pdf文档,目前总共有1000多页(并且还会不断的增加),大家可以免费下载

LeetCode 501. 二叉搜索树中的众数_i++



二叉树的中序遍历解决

LeetCode 501. 二叉搜索树中的众数_二叉搜索树中的众数_02

public void inOrderTraversal(TreeNode node) {
if (node == null)
return;
inOrderTraversal(node.left);
System.out.println(node.val);
inOrderTraversal(node.right);
}

我们来对他进行改造一下

List<Integer> mList = new ArrayList<>();
int curent = 0;//表示当前节点的值
int count = 0;//和当前节点值相同的节点数量
int maxCount = 0;//最大的重复数量

public int[] findMode(TreeNode root) {
inOrderTraversal(root);
int[] res = new int[mList.size()];
//把集合list转化为数组
for (int i = 0; i < mList.size(); i++) {
res[i] = mList.get(i);
}
return res;
}

//递归方式
public void inOrderTraversal(TreeNode node) {
//终止条件判断
if (node == null)
return;
//遍历左子树
inOrderTraversal(node.left);

//下面是对当前节点的一些逻辑操作
int nodeValue = node.val;
if (nodeValue == curent) {
//如果节点值等于curent,count就加1
count++;
} else {
//否则,就表示遇到了一个新的值,curent和count都要
//重新赋值
curent = nodeValue;
count = 1;
}
if (count == maxCount) {
//如果count == maxCount,就把当前节点加入到集合中
mList.add(nodeValue);
} else if (count > maxCount) {
//否则,当前节点的值重复量是最多的,直接把list清空,然后
//把当前节点的值加入到集合中
mList.clear();
mList.add(nodeValue);
maxCount = count;
}

//遍历右子树
inOrderTraversal(node.right);
}

之前在讲到​​373,数据结构-6,树​​的时候,提到二叉树中序遍历的非递归写法

public void inOrderTraversal(TreeNode tree) {
Stack<TreeNode> stack = new Stack<>();
while (tree != null || !stack.isEmpty()) {
while (tree != null) {
stack.push(tree);
tree = tree.left;
}
if (!stack.isEmpty()) {
tree = stack.pop();
System.out.println(tree.val);
tree = tree.right;
}
}
}

再来改造一下

List<Integer> mList = new ArrayList<>();
int curent = 0;
int count = 0;
int maxCount = 0;

public int[] findMode(TreeNode root) {
inOrderTraversal(root);
int[] res = new int[mList.size()];
//把集合list转化为数组
for (int i = 0; i < mList.size(); i++) {
res[i] = mList.get(i);
}
return res;
}

//非递归方式
public void inOrderTraversal(TreeNode tree) {
Stack<TreeNode> stack = new Stack<>();
while (tree != null || !stack.isEmpty()) {
while (tree != null) {
stack.push(tree);
tree = tree.left;
}
if (!stack.isEmpty()) {
tree = stack.pop();
int nodeValue = tree.val;
if (nodeValue == curent) {
//如果节点值等于curent,count就加1
count++;
} else {
//否则,就表示遇到了一个新的值,curent和count都要
//重新赋值
curent = nodeValue;
count = 1;
}
if (count == maxCount) {
//如果count == maxCount,就把当前节点加入到集合中
mList.add(nodeValue);
} else if (count > maxCount) {
//否则,当前节点的值重复量是最多的,直接把list清空,然后
//把当前节点的值加入到集合中
mList.clear();
mList.add(nodeValue);
maxCount = count;
}
tree = tree.right;
}
}
}



总结

做这题首先要搞懂二叉搜索树的中序遍历结果是排序的,这题就容易解了。除了常规的二叉树的中序遍历,我们还可以使用二叉树的Morris中序遍历,具体可以看下​​《488,二叉树的Morris中序和前序遍历》​​。