Skip to content

Commit c856ea7

Browse files
committed
added post_order method on bst
1 parent db269e1 commit c856ea7

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

data_structure/binary_search_tree/binary_search_tree.lua

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,19 @@ function BinarySearchTree:pre_order(callback)
278278
_pre_order(self._root)
279279
end
280280

281+
function BinarySearchTree:post_order(callback)
282+
function _post_order(node)
283+
if node == nil then return end
284+
285+
_post_order(node.left)
286+
_post_order(node.right)
287+
callback(node)
288+
end
289+
290+
291+
_post_order(self._root)
292+
end
293+
281294
function BinarySearchTree:traverse(callback)
282295
self:in_order(callback)
283296
end

data_structure/binary_search_tree/test.lua

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ function _add_datas()
113113
local bst = BinarySearchTree:new()
114114
bst:add(10)
115115
bst:add(5)
116-
bst:add(8)
116+
bst:add(12)
117117
bst:add(4)
118118

119119
return bst
@@ -130,8 +130,8 @@ test('in_order', function()
130130

131131
assert_equal(output[1], 4)
132132
assert_equal(output[2], 5)
133-
assert_equal(output[3], 8)
134-
assert_equal(output[4], 10)
133+
assert_equal(output[3], 10)
134+
assert_equal(output[4], 12)
135135
end)
136136

137137
test('pre_order', function()
@@ -146,5 +146,22 @@ test('pre_order', function()
146146
assert_equal(output[1], 10)
147147
assert_equal(output[2], 5)
148148
assert_equal(output[3], 4)
149-
assert_equal(output[4], 8)
149+
assert_equal(output[4], 12)
150+
end)
151+
152+
test('post_order', function()
153+
local bst = _add_datas()
154+
155+
local output = {}
156+
157+
bst:post_order(function(node)
158+
table.insert(output, node.value)
159+
end)
160+
161+
assert_equal(output[1], 4)
162+
assert_equal(output[2], 5)
163+
assert_equal(output[3], 12)
164+
assert_equal(output[4], 10)
165+
--assert_equal(output[3], 8)
166+
--assert_equal(output[4], 10)
150167
end)

0 commit comments

Comments
 (0)