判斷一棵二叉樹是否是平衡二叉樹:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//二叉平衡搜索樹:
//1.根節點的左子樹與右子樹的高度差不能超過1
//2.這棵二叉樹的每個子樹都符合第一條
function Node(value){
this.value = value;
this.left = null;
this.right = null;
}
var nodeA = new Node("a");
var nodeB = new Node("b");
var nodeC = new Node("c");
var nodeD = new Node("d");
var nodeE = new Node("e");
var nodeF = new Node("f");
var nodeG = new Node("g");
nodeA.left = nodeB;
nodeA.right = nodeC;
nodeB.left = nodeD;
nodeB.right = nodeE;
nodeC.left = nodeF;
nodeC.right = nodeG;
//判斷二叉樹是否平衡
function isBalance(root){
if(root == null) return true;
//獲取左右的深度
var leftDeep = getDeep(root.left);
var rightDeep = getDeep(root.right);
//若左右深度相差大於1,則不是平衡樹
if(Math.abs(leftDeep - rightDeep) > 1){
return false;
}else{
//判斷左右子樹是否平衡
return isBalance(root.left) && isBalance(root.right);
}
}
//獲取樹的深度
function getDeep(root){
if(root == null) return 0;
var leftDeep = getDeep(root.left);
var rightDeep = getDeep(root.right);
return Math.max(leftDeep, rightDeep) + 1;//取兩個深度中最大的一個,加上自身
}
console.log(isBalance(nodeA));
</script>
</body>
</html>
