输入一棵二叉树,判断该二叉树是否是平衡二叉树。
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
//缺点:节点重复遍历,影响效率
function IsBalanced_Solution(pRoot)
{
// write code here
if(pRoot == null) return true;
var left = treeDepth(pRoot.left);
var right = treeDepth(pRoot.right);
return Math.abs(right - left) <= 1 && IsBalanced_Solution(pRoot.left)
&& IsBalanced_Solution(pRoot.right)
}
function treeDepth(root) {
if(!root) return 0;
var left = treeDepth(root.left);
var right = treeDepth(root.right);
return Math.max(left, right) + 1;
}
//在求高度的同时判断是否平衡,如果不平衡就返回-1,否则返回树的高度。
//并且当左子树高度为-1时,就没必要去求右子树的高度了,可以直接一路返回到最上层了
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function IsBalanced_Solution(pRoot)
{
// write code here
return getDepth(pRoot) != -1
}
function getDepth(root) {
if(root == null) return 0;
var left = getDepth(root.left);
if(left == -1) return -1;
var right = getDepth(root.right);
if(right == -1) return -1;
return Math.abs(right - left) > 1 ? -1 : 1 + Math.max(left, right);
}