二叉排序树
二叉排序树是一颗具有排序效果的二叉树。
左子树存在时,左子树中所有节点的值均小于根节点的值。
右子树存在时,右子树中所有节点的值均大于根节点的值。
每个子树也都是二叉排序树。
1.构建二叉排序树
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
//创建指定长度的随机数数组
function createRandomArr(len) {
let set = new Set();
while (set.size < len) {
set.add(Math.ceil(Math.random() * len * 10));
}
return Array.from(set);
}
let arr = createRandomArr(7);
console.log(arr);//[ 45, 21, 49, 64, 39, 28, 58]
//根据指定数组,构建二叉排序树
function createSearchTree(arr) {
if (!arr || !arr.length) {
return null;
}
//以第一个数为根节点
let root = new Node(arr[0]);
for (let i = 1; i < arr.length; i++) {
addNode(root, arr[i]);
}
return root;
}
//添加节点
function addNode(root, num) {
if (!root || !num) {
return;
}
if (root.val === num) {
return;
}
if (root.val > num) {
if (!root.left) {
root.left = new Node(num);
} else {
addNode(root.left, num);
}
} else {
if (!root.right) {
root.right = new Node(num);
} else {
addNode(root.right, num);
}
}
}
let newTree = createSearchTree(arr);
console.log(JSON.stringify(newTree));
构建的二叉排序树如下图:
2.判断一棵二叉排序树是否是二叉平衡树
二叉平衡树是每个节点的左子树和右子树的高度差不超过1的二叉排序树。
//获取一棵二叉排序树的高度
function getDeep(root) {
if (!root) {
return 0;
}
let leftDeep = getDeep(root.left);
let rightDeep = getDeep(root.right);
return Math.max(leftDeep, rightDeep) + 1;
}
//判断二叉排序树是否是二叉平衡树
function isBlance(root) {
if (!root) {
return true;
}
let leftDeep = getDeep(root.left);
let rightDeep = getDeep(root.right);
if (Math.abs(leftDeep-rightDeep) > 1) {
return false;
} else {
return isBlance(root.left) && isBlance(root.right);
}
}
console.log(isBlance(newTree));