Skip to content

Instantly share code, notes, and snippets.

@hillal20
Last active September 13, 2018 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hillal20/98d92185b2c9f1081394bba8aed8a170 to your computer and use it in GitHub Desktop.
Save hillal20/98d92185b2c9f1081394bba8aed8a170 to your computer and use it in GitHub Desktop.
DiscreteSnappyScientist created by hillal20 - https://repl.it/@hillal20/DiscreteSnappyScientist
class BinaryTreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
insertLeft(value) {
this.left = new BinaryTreeNode(value);
return this.left;
}
insertRight(value) {
this.right = new BinaryTreeNode(value);
return this.right;
}
}
/*
A recursive solution
How would you solve this iteratively?
*/
const checkBalanced = (rootNode) => {
// An empty tree is balanced by default
if (!rootNode) return true;
// recursive helper function to check the min depth of the tree
const minDepth = (node) => {
if (!node) return 0;
return 1 + Math.min(minDepth(node.left), minDepth(node.right));
};
// recursive helper function to check the max depth of the tree
const maxDepth = (node) => {
if (!node) return 0;
return 1 + Math.max(maxDepth(node.left), maxDepth(node.right));
}
return (maxDepth(rootNode) - minDepth(rootNode) === 0);
};
/* Some console.log tests */
const root = new BinaryTreeNode(5);
console.log('root ===>5',root)
console.log(checkBalanced(root)); // should print true
root.insertLeft(10);
console.log('root ===>10',root)
console.log(checkBalanced(root)); // should print false
root.insertRight(11);
console.log('root ===>',root)
console.log(checkBalanced(root)); // should print true;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment