二叉树day10
98. 验证二叉搜索树
/**
* 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 {
TreeNode pre = null;
public boolean isValidBST(TreeNode root) {
return inOrder(root);
}
private boolean inOrder(TreeNode root) {
if (root == null) return true;
boolean left = inOrder(root.left);
if (pre != null && pre.val >= root.val) return false;
pre = root;
boolean right = inOrder(root.right);
return left && right;
}
}
//中序迭代 得到是一个有序序列 且无重复元素
// class Solution {
// public boolean isValidBST(TreeNode root) {
// TreeNode pre = null;
// Deque<TreeNode> stack = new LinkedList<>();
// stack.push(root);
// while (!stack.isEmpty()) {
// TreeNode cur = stack.peek();
// while (cur != null) {
// stack.push(cur.left);
// cur = cur.left;
// }
// //空指针退栈
// stack.pop();
// if (!stack.isEmpty()) {
// cur = stack.pop();
// if (pre != null && pre.val >= cur.val) return false;
// pre = cur;
// stack.push(cur.right);
// }
// }
// return true;
// }
// }
530. 二叉搜索树的最小绝对差
//中序递归 中序遍历搜索二叉树的结点是一个递增序列
class Solution {
TreeNode pre = null;
int res = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if (root.left != null) res = getMinimumDifference(root.left);
if (pre != null) res = Math.min(root.val - pre.val, res);
pre = root;
if (root.right != null) res = getMinimumDifference(root.right);
return res;
}
}
501. 二叉搜索树中的众数
//使用额外空间 遍历树用HashMap存出现次数
//不用额外空间 中序遍历搜索树得到的是一个有序序列 直接统计连续值即可
class Solution {
private TreeNode pre = null;
private List<Integer> resList;
private int count = 0;
private int maxCount = 0;
public int[] findMode(TreeNode root) {
resList = new ArrayList<>();
inOrder(root);
int size = resList.size();
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = resList.get(i);
}
return res;
}
private void inOrder(TreeNode root) {
if (root == null) return;
if (root.left != null) inOrder(root.left);
if (pre == null) count++;
else if (root.val == pre.val) count++;
//重新开始计数
else count = 1;
pre = root;
if (count > maxCount) {
maxCount = count;
resList.clear();
resList.add(root.val);
} else if(count == maxCount) {
resList.add(root.val);
}
if (root.right != null) inOrder(root.right);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步