Last active
January 3, 2016 01:19
-
-
Save jack-wong-build/8388391 to your computer and use it in GitHub Desktop.
Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.
This file contains 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
var isBalanced = function(node){ | |
var maxDepth = function(node){ | |
if (node === undefined){ | |
return 0; | |
} | |
return 1 + Math.max(maxDepth(node.next[0]), maxDepth(node.next[1])); | |
} | |
var minDepth = function(node){ | |
if (node === undefined){ | |
return 0; | |
} | |
return 1 + Math.min(minDepth(node.next[0]), minDepth(node.next[1])); | |
} | |
return (maxDepth(node) - minDepth(node) <= 1); | |
} | |
// var makeNode = function(key, value){ | |
// var obj = {"key": key, | |
// "value": value, | |
// "next": [], | |
// visit: false}; | |
// return obj; | |
// } | |
// create a balanced tree | |
// var root = makeNode("1", "apple"); | |
// var node1 = makeNode("2", "orange"); | |
// var node2 = makeNode("3", "kiwi"); | |
// root.next.push(node1); | |
// root.next.push(node2); | |
// var node1 = makeNode("4", "banana"); | |
// var node2 = makeNode("5", "blueberry"); | |
// root.next[0].next.push(node1); | |
// root.next[0].next.push(node2); | |
// var node1 = makeNode("6", "grape"); | |
// var node2 = makeNode("7", "pineapple"); | |
// root.next[1].next.push(node1); | |
// root.next[1].next.push(node2); | |
// // should be balanced | |
// console.log(isBalanced(root)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment