mirror of
https://github.com/donnemartin/interactive-coding-challenges
synced 2026-01-11 03:48:03 +00:00
Move tree bfs to a class
This commit is contained in:
@@ -97,16 +97,20 @@
|
||||
"from collections import deque\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def bfs(root, visit_func):\n",
|
||||
" queue = deque()\n",
|
||||
" queue.append(root)\n",
|
||||
" while queue:\n",
|
||||
" node = queue.popleft()\n",
|
||||
" visit_func(node)\n",
|
||||
" if node.left is not None:\n",
|
||||
" queue.append(node.left)\n",
|
||||
" if node.right is not None:\n",
|
||||
" queue.append(node.right)"
|
||||
"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(self.root)\n",
|
||||
" while queue:\n",
|
||||
" node = queue.popleft()\n",
|
||||
" visit_func(node)\n",
|
||||
" if node.left is not None:\n",
|
||||
" queue.append(node.left)\n",
|
||||
" if node.right is not None:\n",
|
||||
" queue.append(node.right)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -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",
|
||||
|
||||
Reference in New Issue
Block a user