From 6b269d0f45268ed55a5d4242c035822b9fe21522 Mon Sep 17 00:00:00 2001 From: Donne Martin Date: Sun, 16 Aug 2015 08:21:11 -0400 Subject: [PATCH] Updated bst to keep track of its parent and to return the node it inserts. --- graphs_trees/bst/bst.py | 9 +++++++-- graphs_trees/bst/bst_challenge.ipynb | 4 +++- graphs_trees/bst/bst_solution.ipynb | 13 ++++++++++--- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/graphs_trees/bst/bst.py b/graphs_trees/bst/bst.py index 38d6814..ce6a16b 100644 --- a/graphs_trees/bst/bst.py +++ b/graphs_trees/bst/bst.py @@ -4,6 +4,7 @@ class Node(object): self.data = data self.left = None self.right = None + self.parent = None def __str__(self): return str(self.data) @@ -13,10 +14,14 @@ def insert(root, data): if data <= root.data: if root.left is None: root.left = Node(data) + root.left.parent = root + return root.left else: - insert(root.left, data) + return insert(root.left, data) else: if root.right is None: root.right = Node(data) + root.right.parent = root + return root.right else: - insert(root.right, data) \ No newline at end of file + return insert(root.right, data) \ No newline at end of file diff --git a/graphs_trees/bst/bst_challenge.ipynb b/graphs_trees/bst/bst_challenge.ipynb index 5110969..df23770 100644 --- a/graphs_trees/bst/bst_challenge.ipynb +++ b/graphs_trees/bst/bst_challenge.ipynb @@ -38,7 +38,9 @@ "* Can we assume all left descendents <= n < all right descendents?\n", " * Yes\n", "* For simplicity, can we use just a Node class without a wrapper Tree class?\n", - " * Yes" + " * Yes\n", + "* Do we have to keep track of the parent nodes?\n", + " * This is optional" ] }, { diff --git a/graphs_trees/bst/bst_solution.ipynb b/graphs_trees/bst/bst_solution.ipynb index 183b1be..36facb0 100644 --- a/graphs_trees/bst/bst_solution.ipynb +++ b/graphs_trees/bst/bst_solution.ipynb @@ -38,7 +38,9 @@ "* Can we assume all left descendents <= n < all right descendents?\n", " * Yes\n", "* For simplicity, can we use just a Node class without a wrapper Tree class?\n", - " * Yes" + " * Yes\n", + "* Do we have to keep track of the parent nodes?\n", + " * This is optional" ] }, { @@ -108,6 +110,7 @@ " self.data = data\n", " self.left = None\n", " self.right = None\n", + " self.parent = None\n", "\n", " def __str__(self):\n", " return str(self.data)\n", @@ -117,13 +120,17 @@ " if data <= root.data:\n", " if root.left is None:\n", " root.left = Node(data)\n", + " root.left.parent = root\n", + " return root.left\n", " else:\n", - " insert(root.left, data)\n", + " return insert(root.left, data)\n", " else:\n", " if root.right is None:\n", " root.right = Node(data)\n", + " root.right.parent = root\n", + " return root.right\n", " else:\n", - " insert(root.right, data)" + " return insert(root.right, data)" ] }, {