Created
February 18, 2015 05:01
-
-
Save alexhawkins/7d48613579f27a7aae7b to your computer and use it in GitHub Desktop.
Balancing A Binary Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Write a funciton to check to see if a binary Tree is balanced. | |
For the purposes of this tree, a balanced tree is defined to be a | |
tree such that the heights of the subtrees of any node never differ | |
by more than one */ | |
BinaryTree.prototype.isBalanced = function() { | |
var checkHeight = function(current) { | |
if (!current) return 0 //height = 0; | |
//check to see if left side is balanced | |
var leftHeight = checkHeight(current.left); | |
if (leftHeight === -1) return -1; | |
//check to see if right side is balanced | |
var rightHeight = checkHeight(current.right); | |
if (rightHeight === -1) return -1; | |
//check if current node is balanced | |
var heightDiff = Math.abs(leftHeight - rightHeight); | |
if (heightDiff > 1) | |
return -1 // not balanced | |
else | |
return Math.max(leftHeight, rightHeight) + 1; | |
}; | |
return checkHeight(this.root) === -1 ? false : true; | |
}; | |
//TESTS | |
var bt = new BinaryTree(); | |
bt.add(10, 14, 6, 11, 18, 5, 8, 21, 7, 19); | |
console.log(bt); | |
console.log('BALANCED: ', bt.isBalanced()) //BALANCED: false; | |
BinaryTree.prototype.getHeight = function() { | |
var recurse = function(current) { | |
if (!current) return 0; | |
var leftHeight = recurse(current.left) + 1; | |
var rightHeight = recurse(current.right) + 1; | |
return Math.max(leftHeight, rightHeight); | |
}; | |
return recurse(this.root); | |
}; | |
var height = bt.getHeight(); | |
console.log(height); // 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment