{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Solution Notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Problem: Find the in-order successor of a given node in a binary search tree.\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",
    "* If there is no successor, do we return None?\n",
    "    * Yes\n",
    "* If the input is None, should we throw an exception?\n",
    "    * Yes\n",
    "* Can we assume we already have a Node class that keeps track of parents?\n",
    "    * Yes\n",
    "* Can we assume this fits memory?\n",
    "    * Yes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test Cases\n",
    "\n",
    "<pre>\n",
    "          _5_\n",
    "        /     \\\n",
    "       3       8\n",
    "      / \\    /   \\\n",
    "     2   4  6    12\n",
    "    /        \\   / \\\n",
    "   1          7 10  15\n",
    "               /\n",
    "              9\n",
    "\n",
    "In: None  Out: Exception\n",
    "In: 4     Out: 5\n",
    "In: 5     Out: 6\n",
    "In: 8     Out: 9\n",
    "In: 15    Out: None\n",
    "</pre>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Algorithm\n",
    "\n",
    "* If the node has a right subtree, return the left-most node in the right subtree\n",
    "* Else, go up until you find a node that is its parent's left node\n",
    "    * If you get to the root (ie node.parent is None), return None\n",
    "        * The original input node must be the largest in the tree\n",
    "    * Else, return the parent\n",
    "    \n",
    "Complexity:\n",
    "* Time: O(h), where h is the height of the tree\n",
    "* Space: O(h), where h is the recursion depth (tree height), or O(1) if using an iterative approach"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "%run ../bst/bst.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class BstSuccessor(object):\n",
    "\n",
    "    def get_next(self, node):\n",
    "        if node is None:\n",
    "            raise TypeError('node cannot be None')\n",
    "        if node.right is not None:\n",
    "            return self._left_most(node.right)\n",
    "        else:\n",
    "            return self._next_ancestor(node)\n",
    "\n",
    "    def _left_most(self, node):\n",
    "        if node.left is not None:\n",
    "            return self._left_most(node.left)\n",
    "        else:\n",
    "            return node.data\n",
    "\n",
    "    def _next_ancestor(self, node):\n",
    "        if node.parent is not None:\n",
    "            if node.parent.data > node.data:\n",
    "                return node.parent.data\n",
    "            else:\n",
    "                return self._next_ancestor(node.parent)\n",
    "        # We reached the root, the original input node\n",
    "        # must be the largest element in the tree.\n",
    "        return None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unit Test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting test_bst_successor.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile test_bst_successor.py\n",
    "from nose.tools import assert_equal\n",
    "from nose.tools import raises\n",
    "\n",
    "\n",
    "class TestBstSuccessor(object):\n",
    "\n",
    "    @raises(Exception)\n",
    "    def test_bst_successor_empty(self):\n",
    "        bst_successor = BstSuccessor()\n",
    "        bst_successor.get_next(None)\n",
    "\n",
    "    def test_bst_successor(self):\n",
    "        nodes = {}\n",
    "        node = Node(5)\n",
    "        nodes[5] = node\n",
    "        bst = Bst(nodes[5])\n",
    "        nodes[3] = bst.insert(3)\n",
    "        nodes[8] = bst.insert(8)\n",
    "        nodes[2] = bst.insert(2)\n",
    "        nodes[4] = bst.insert(4)\n",
    "        nodes[6] = bst.insert(6)\n",
    "        nodes[12] = bst.insert(12)\n",
    "        nodes[1] = bst.insert(1)\n",
    "        nodes[7] = bst.insert(7)\n",
    "        nodes[10] = bst.insert(10)\n",
    "        nodes[15] = bst.insert(15)\n",
    "        nodes[9] = bst.insert(9)\n",
    "\n",
    "        bst_successor = BstSuccessor()\n",
    "        assert_equal(bst_successor.get_next(nodes[4]), 5)\n",
    "        assert_equal(bst_successor.get_next(nodes[5]), 6)\n",
    "        assert_equal(bst_successor.get_next(nodes[8]), 9)\n",
    "        assert_equal(bst_successor.get_next(nodes[15]), None)\n",
    "\n",
    "        print('Success: test_bst_successor')\n",
    "\n",
    "\n",
    "def main():\n",
    "    test = TestBstSuccessor()\n",
    "    test.test_bst_successor()\n",
    "    test.test_bst_successor_empty()\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Success: test_bst_successor\n"
     ]
    }
   ],
   "source": [
    "%run -i test_bst_successor.py"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
