二叉搜索树的最小绝对差
需要领悟一下二叉树遍历上双指针操作,优先掌握递归
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
/**
* 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 {
public int getMinimumDifference(TreeNode root) {
List<Integer> list = new ArrayList<>();
travel(root, list);
int min = Integer.MAX_VALUE;
int num = 0;
for(int i = 0; i < list.size() - 1; i++){
num = Math.abs(list.get(i + 1) - list.get(i));
if(min > num){
min = num;
}
}
return min;
}
public void travel(TreeNode root, List<Integer> list){
if(root == null) return;
travel(root.left, list);
list.add(root.val);
travel(root.right, list);
}
}
以上代码是把二叉搜索树转化为有序数组了,其实在二叉搜素树中序遍历的过程中,我们就可以直接计算了。
需要用一个pre节点记录一下cur节点的前一个节点。
/**
* 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 result = Integer.MAX_VALUE;
TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
travel(root);
return result;
}
public void travel(TreeNode root){
if(root == null) return;
travel(root.left);
if(pre != null){
result = Math.min(result,root.val - pre.val);
}
pre = root;
travel(root.right);
}
}
501.二叉搜索树中的众数
和 530差不多双指针思路,不过这里涉及到一个很巧妙的代码技巧。
给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
结点左子树中所含节点的值 小于等于 当前节点的值结点右子树中所含节点的值 大于等于 当前节点的值左子树和右子树都是二叉搜索树
下面代码36到41是重点!一定要好好理解,很巧妙
/**
* 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 {
List<Integer> list = new ArrayList<>();
int count = 0;
int maxCount = 1;
TreeNode pre = null;
public int[] findMode(TreeNode root) {
travel(root);
return list.stream().mapToInt(Integer::intValue).toArray();
}
public void travel(TreeNode root){
if(root == null) return;
travel(root.left);
if(pre == null){
count = 1;
}else if(pre.val == root.val){
count++;
}else{
count = 1;
}
pre = root;
if(count == maxCount){
list.add(root.val);
}else if(count > maxCount){
maxCount = count;
list.clear();
list.add(root.val);
}
travel(root.right);
}
}