{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Nodes and References Implementation of a Tree\n", "\n", "In this notebook is the code corresponding to the lecture for implementing the representation of a Tree as a class with nodes and references!" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class BinaryTree(object):\n", " def __init__(self,rootObj):\n", " self.key = rootObj\n", " self.leftChild = None\n", " self.rightChild = None\n", "\n", " def insertLeft(self,newNode):\n", " if self.leftChild == None:\n", " self.leftChild = BinaryTree(newNode)\n", " else:\n", " t = BinaryTree(newNode)\n", " t.leftChild = self.leftChild\n", " self.leftChild = t\n", "\n", " def insertRight(self,newNode):\n", " if self.rightChild == None:\n", " self.rightChild = BinaryTree(newNode)\n", " else:\n", " t = BinaryTree(newNode)\n", " t.rightChild = self.rightChild\n", " self.rightChild = t\n", "\n", "\n", " def getRightChild(self):\n", " return self.rightChild\n", "\n", " def getLeftChild(self):\n", " return self.leftChild\n", "\n", " def setRootVal(self,obj):\n", " self.key = obj\n", "\n", " def getRootVal(self):\n", " return self.key" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see some examples of creating a tree and assigning children. Note that some outputs are Trees themselves!" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a\n", "None\n", "<__main__.BinaryTree object at 0x104779c10>\n", "b\n", "<__main__.BinaryTree object at 0x103b42c50>\n", "c\n", "hello\n" ] } ], "source": [ "from __future__ import print_function\n", "\n", "r = BinaryTree('a')\n", "print(r.getRootVal())\n", "print(r.getLeftChild())\n", "r.insertLeft('b')\n", "print(r.getLeftChild())\n", "print(r.getLeftChild().getRootVal())\n", "r.insertRight('c')\n", "print(r.getRightChild())\n", "print(r.getRightChild().getRootVal())\n", "r.getRightChild().setRootVal('hello')\n", "print(r.getRightChild().getRootVal())" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.11" } }, "nbformat": 4, "nbformat_minor": 0 }