【算法】实现平衡二叉树

143 阅读1分钟

判断「平衡二叉树」的 2 个条件:

  1. 是「二叉排序树」
  2. 任何一个节点的左子树或者右子树都是「平衡二叉树」(左右高度差小于等于 1)

在这里插入图片描述

(1)下图不是「平衡二叉树」因为它不是「二叉排序树」违反第 1 条件

image-20210110143603854

(2)下图不是「平衡二叉树」因为有节点子树高度差大于 1 违法第 2 条件 image-20210105164337734

(3)下图是「平衡二叉树」因为符合 1、2 条件 image-20210110143622791

function Tree(value) {
	this.value = value;
	this.left = null;
	this.right = null;
}
const a = new Tree("A");
const b = new Tree("B");
const c = new Tree("C");
const d = new Tree("D");
const e = new Tree("E");
const f = new Tree("F");
const g = new Tree("G");

a.left = b;
a.right = c;
b.left = d;
b.right = e;
c.left = f;
c.right = g;

function getDeep(root) {
	if(root == null) return 0;
	let leftDeep = getDeep(root.left);
	let rightDeep = getDeep(root.right);
	return Math.max(leftDeep, rightDeep) + 1;
}
console.log(getDeep(a))

// 栈执行顺序:
// a.left -> b     1    leftDeep
// b.left -> d     2    leftDeep
// d.left -> 0
// d.right -> 0  
// b.right -> e    1    rightDeep
// e.left -> 0
// e.right -> 0
// a.right -> c    2    rightDeep
// c.left -> f     3    leftDeep
// f.left -> 0
// f.right -> 0
// c.right -> g    3    rightDeep
// g.left -> 0
// g.right -> 0

function isBalance(root) {
	if(root == null) return true;
	let leftDeep = getDeep(root.left);
	let rightDeep = getDeep(root.right);
	if(Math.abs(leftDeep - rightDeep > 1)) {
		return false;
	}else {
		return isBalance(root.left) && isBalance(root.right);
 	}
}
console.log(isBalance(b));