一、二叉搜索树中的搜索
// 二叉搜索树中的搜索
// 二叉搜索树满足如下:
// 左子树所有节点的元素值均小于根的元素值;
// 右子树所有节点的元素值均大于根的元素值
var searchBST = function(root, val) {
if(!root) return null;
if(val === root.val){
return root;
}
return searchBST(val < root.val ? root.left:root.right,val)
};
二、验证二叉搜索树
// 定一个数组存放中序遍历的顺序然后在数组中进行比较
var isValidBST = function(root) {
let checkArr = [];
// 二叉树的中序遍历,左根右 顺序
let Traverse = function(root) {
if(root == null)
return
Traverse(root.left);
checkArr.push(root.val);
Traverse(root.right);
}
Traverse(root)
for(let i = 1;i < checkArr.length;i ++){
if(checkArr[i-1] >= checkArr[i])
return false;
}
return true;
};
三、二叉搜索树的最小绝对差
代码如下(示例):
//二叉搜索树中的最小绝对值
//通过中序遍历将二叉树转化为数组,在数组中进行比较
var getMinimumDifference = function(root) {
let res = Infinity
let preNode = null
const inorder = (node) => {
if(!node) return
inorder(node.left)
// 更新res
if(preNode) res = Math.min(res, node.val - preNode.val)
// 记录前一个节点
preNode = node
inorder(node.right)
}
inorder(root)
return res
};
四、二叉搜索树的众数
//二叉树中的众数
// 通过中序遍历将二叉树的值存储在数组中,遍历数组中当前值和上一个值比较是否相同。相同则加1,不相同count就是1表示当前是一个新元素
//每比较一次就要看是否更新最大值
//如果count>max就更新最大值,清空结果数组,添加新的数据到结果数组
//如果count= max就说明当前出新次数和之前出现的次数一样多,直接添加新数据到结果数组
var findMode = function(root) {
let prenode = null;
let count = 1;
let max = 1;
let res = [];
const helper = (root) => {
if(!root) return;
helper(root.left);
if(prenode) {
if(root.val==prenode.val) count++;
else count=1;
}
if(count > max){
max = count;
res = [];
res.push(root.val);
}else if(count == max) res.push(root.val);
prenode = root;
helper(root.right);
}
helper(root);
return res;
};
五、把二叉搜索树转换为累加树
// 把二叉树转换为累加树
// 先遍历所有的结点,将当前结点与前一个结点相加获得大于当前结点的值
// 先遍历右节点,逆向输出结点的值
var convertBST = function(root) {
if(!root) return null;
// 创建一个数组存放各结点
let res = [];
let node = root;
let prenode = null;
while(node || res.length) {
while(node) {
res.push(node)
node = node.right;
}
node = res.pop();
if(prenode) {
node.val += prenode.val;
}
prenode = node;
node = node.left;
}
return root;
};