Skip to content

Instantly share code, notes, and snippets.

@AlexeiDarmin
Created November 18, 2018 18:29
Show Gist options
  • Save AlexeiDarmin/17f2c01742b52db9f2a8db70f4c41cab to your computer and use it in GitHub Desktop.
Save AlexeiDarmin/17f2c01742b52db9f2a8db70f4c41cab to your computer and use it in GitHub Desktop.
Check if a binary tree is balanced, the heights of two subtrees may never differ by more than one
/*
Check balanced: Implement a function to check if a binary tree is balanced. For the purposes of
this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any
node never differ by more than one.
*/
// const myTree = buildTree([1,2,3,4,5,6,7,8, 9, 10, 11, 12, 13, 14])
const myTree = new BinaryNode(1)
myTree.rightChild = new BinaryNode(2)
myTree.rightChild.rightChild = new BinaryNode(3)
function isBalanced<T>(head: BinaryNode<T>) {
const leftHeight = getBalancedHeight(head.leftChild)
const rightHeight = getBalancedHeight(head.rightChild)
if (leftHeight === -1 || rightHeight === -1) return false
return (Math.abs(leftHeight - rightHeight) <= 1)
}
function getBalancedHeight<T>(node: BinaryNode<T>) {
if (!node) return 0
const leftHeight = getBalancedHeight(node.leftChild)
const rightHeight = getBalancedHeight(node.rightChild)
if (leftHeight === -1 || rightHeight === -1) return -1
if (Math.abs(leftHeight - rightHeight) > 1) return -1
return Math.max(leftHeight, rightHeight) + 1
}
console.log('isBalanced', isBalanced(myTree))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment