Tree traversal: Difference between revisions
Content deleted Content added
Thundergnat (talk | contribs) m fix markup |
→{{header|Lua}}: simpler, easier to understand |
||
Line 6,935: | Line 6,935: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
<syntaxhighlight lang="lua"> |
<syntaxhighlight lang="lua"> |
||
local function |
local function depth_first(tr, a, b, c, flat_list) |
||
for _, val in ipairs({a, b, c}) do |
|||
if type(tr[val]) == "table" then |
|||
⚫ | |||
depth_first(tr[val], a, b, c, flat_list) |
|||
⚫ | |||
elseif type(tr[val]) ~= "nil" then |
|||
⚫ | |||
end -- if |
|||
end -- for |
|||
return flat_list |
|||
end |
end |
||
local function flatten_pre_order(tr) return depth_first(tr, 1, 2, 3, {}) end |
|||
local function flatten_in_order(tr) return depth_first(tr, 2, 1, 3, {}) end |
|||
local function flatten_post_order(tr) return depth_first(tr, 2, 3, 1, {}) end |
|||
local function flatten_level_order(tr) |
|||
-- Node class |
|||
local |
local flat_list, queue = {}, {tr} |
||
⚫ | |||
Node.__index = Node |
|||
⚫ | |||
if type(node) == "table" then |
|||
function Node:order(order) |
|||
⚫ | |||
local r = {} |
|||
⚫ | |||
append(r, type(self[order[1]]) == "table" and self[order[1]]:order(order) or {self[order[1]]}) |
|||
table.insert(queue, node[3]) -- enqueue |
|||
append(r, type(self[order[2]]) == "table" and self[order[2]]:order(order) or {self[order[2]]}) |
|||
else |
|||
append(r, type(self[order[3]]) == "table" and self[order[3]]:order(order) or {self[order[3]]}) |
|||
⚫ | |||
⚫ | |||
end |
end -- if |
||
⚫ | |||
⚫ | |||
function Node:levelorder() |
|||
local levelorder = {} |
|||
local queue = {self} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
end |
|||
return levelorder |
|||
end |
|||
-- Node creator |
|||
local function new(value, left, right) |
|||
return value and setmetatable({ |
|||
value, |
|||
(type(left) == "table") and new(unpack(left)) or new(left), |
|||
(type(right) == "table") and new(unpack(right)) or new(right), |
|||
}, Node) or nil |
|||
end |
end |
||
-- Example |
-- Example |
||
local tree = |
local tree = {1, {2, {4, 7}, 5}, {3, {6, 8, 9}}} |
||
print(" |
print("Pre order: " .. table.concat(flatten_pre_order(tree), " ")) |
||
print(" |
print("In order: " .. table.concat(flatten_in_order(tree), " ")) |
||
print(" |
print("Post order: " .. table.concat(flatten_post_order(tree), " ")) |
||
print(" |
print("Level order: " .. table.concat(flatten_level_order(tree), " ")) |
||
</syntaxhighlight> |
|||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |