"<small><i>This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).</i></small>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Solution Notebook"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Problem: Check if a binary tree is balanced.\n",
"\n",
"* [Constraints](#Constraints)\n",
"* [Test Cases](#Test-Cases)\n",
"* [Algorithm](#Algorithm)\n",
"* [Code](#Code)\n",
"* [Unit Test](#Unit-Test)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Constraints\n",
"\n",
"* Is a balanced tree one where the heights of two sub trees of any node doesn't differ by more than 1?\n",
" * Yes\n",
"* Can we assume we already have a Node class with an insert method?\n",
" * Yes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Test Cases\n",
"\n",
"* 5, 3, 8, 1, 4 -> Yes\n",
"* 5, 3, 8, 9, 10 -> No"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Algorithm\n",
"\n",
"The algorithm will be similar to where we get the height of a tree as seen in [here](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/tree_height/height_solution.ipynb).\n",
"\n",
"However, we could check whether the tree is balanced while also checking for the heights.\n",
"\n",
"* Base case: If the root is None, return 0\n",
"* Check the height of `root.left`, if -1, return -1\n",
"* Check the height of `root.right`, if -1, return -1\n",
"* If the height differences is greater than 1, return -1\n",
"* Otherwise, return 1 + max(left height, right height)\n",