您的位置:首页 > Web前端 > JavaScript

Balanced Binary Tree

2016-06-13 02:12 483 查看
Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Tags

Tree, DFS

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Check height of the left and right tree difference.

/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/

function maxHeight(node) {
if (node === null) {
return 0;
}

if (node.left === null && node.right === null) {
return 1;
}

return Math.max(maxHeight(node.left), maxHeight(node.right)) + 1;
}

var isBalanced = function (root) {
if (root === null || (root.left === null && root.right === null)) {
return true;
}

return (Math.abs(maxHeight(root.left) - maxHeight(root.right)) <= 1) && isBalanced(root.left) && isBalanced(root.right);
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息