mirror of
https://github.com/donnemartin/interactive-coding-challenges.git
synced 2024-03-22 13:11:13 +08:00
Move tree bfs to a class
This commit is contained in:
parent
b91b6a437b
commit
10a404c7ae
|
@ -87,7 +87,9 @@
|
|||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def bfs(self, visit_func):\n",
|
||||
"class BstBfs(Bst):\n",
|
||||
"\n",
|
||||
" def bfs(self, visit_func):\n",
|
||||
" # TODO: Implement me\n",
|
||||
" pass"
|
||||
]
|
||||
|
@ -128,12 +130,12 @@
|
|||
" self.results = Results()\n",
|
||||
"\n",
|
||||
" def test_bfs(self):\n",
|
||||
" node = Node(5)\n",
|
||||
" insert(node, 2)\n",
|
||||
" insert(node, 8)\n",
|
||||
" insert(node, 1)\n",
|
||||
" insert(node, 3)\n",
|
||||
" bfs(node, self.results.add_result)\n",
|
||||
" bst = BstBfs(Node(5))\n",
|
||||
" bst.insert(2)\n",
|
||||
" bst.insert(8)\n",
|
||||
" bst.insert(1)\n",
|
||||
" bst.insert(3)\n",
|
||||
" bst.bfs(self.results.add_result)\n",
|
||||
" assert_equal(str(self.results), '[5, 2, 8, 1, 3]')\n",
|
||||
"\n",
|
||||
" print('Success: test_bfs')\n",
|
||||
|
|
|
@ -97,9 +97,13 @@
|
|||
"from collections import deque\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def bfs(root, visit_func):\n",
|
||||
"class BstBfs(Bst):\n",
|
||||
"\n",
|
||||
" def bfs(self, visit_func):\n",
|
||||
" if self.root is None:\n",
|
||||
" raise Exception('root is None')\n",
|
||||
" queue = deque()\n",
|
||||
" queue.append(root)\n",
|
||||
" queue.append(self.root)\n",
|
||||
" while queue:\n",
|
||||
" node = queue.popleft()\n",
|
||||
" visit_func(node)\n",
|
||||
|
@ -153,12 +157,12 @@
|
|||
" self.results = Results()\n",
|
||||
"\n",
|
||||
" def test_bfs(self):\n",
|
||||
" node = Node(5)\n",
|
||||
" insert(node, 2)\n",
|
||||
" insert(node, 8)\n",
|
||||
" insert(node, 1)\n",
|
||||
" insert(node, 3)\n",
|
||||
" bfs(node, self.results.add_result)\n",
|
||||
" bst = BstBfs(Node(5))\n",
|
||||
" bst.insert(2)\n",
|
||||
" bst.insert(8)\n",
|
||||
" bst.insert(1)\n",
|
||||
" bst.insert(3)\n",
|
||||
" bst.bfs(self.results.add_result)\n",
|
||||
" assert_equal(str(self.results), '[5, 2, 8, 1, 3]')\n",
|
||||
"\n",
|
||||
" print('Success: test_bfs')\n",
|
||||
|
|
|
@ -7,12 +7,12 @@ class TestBfs(object):
|
|||
self.results = Results()
|
||||
|
||||
def test_bfs(self):
|
||||
node = Node(5)
|
||||
insert(node, 2)
|
||||
insert(node, 8)
|
||||
insert(node, 1)
|
||||
insert(node, 3)
|
||||
bfs(node, self.results.add_result)
|
||||
bst = BstBfs(Node(5))
|
||||
bst.insert(2)
|
||||
bst.insert(8)
|
||||
bst.insert(1)
|
||||
bst.insert(3)
|
||||
bst.bfs(self.results.add_result)
|
||||
assert_equal(str(self.results), '[5, 2, 8, 1, 3]')
|
||||
|
||||
print('Success: test_bfs')
|
||||
|
|
Loading…
Reference in New Issue
Block a user