|
| 1 | +-- Search tree class handler implementation |
| 2 | + |
| 3 | +local PATH = (...):gsub('handlers.tree_handler$','') |
| 4 | +local class = require (PATH .. '.utils.class') |
| 5 | + |
| 6 | + |
| 7 | +local tree = class () |
| 8 | + |
| 9 | +-- Tree initialization |
| 10 | +function tree:initialize() |
| 11 | + self.nodes = {} |
| 12 | +end |
| 13 | + |
| 14 | +-- Adds a node in the tree |
| 15 | +function tree:addNode(name, parent, value) |
| 16 | + assert(not self.nodes[name], 'node already exist') |
| 17 | + local node = { |
| 18 | + name = name, value = value, |
| 19 | + parent = parent, children = {} |
| 20 | + } |
| 21 | + if parent then |
| 22 | + parent = self:getNode(parent) |
| 23 | + assert(parent, 'parent not found') |
| 24 | + table.insert(parent.children, node) |
| 25 | + end |
| 26 | + if not self.head then self.head = node end |
| 27 | + table.insert(self.nodes, node) |
| 28 | +end |
| 29 | + |
| 30 | +-- Get the node by its name |
| 31 | +function tree:getNode(name) |
| 32 | + for i, node in ipairs(self.nodes) do |
| 33 | + if node.name == name then return node end |
| 34 | + end |
| 35 | +end |
| 36 | + |
| 37 | +-- Checks if a given node is terminal (leaf) in the search tree |
| 38 | +function tree:isLeaf(node) |
| 39 | + return #node.children == 0 |
| 40 | +end |
| 41 | + |
| 42 | +-- Returns the node value |
| 43 | +function tree:heuristic(node) |
| 44 | + return node.value |
| 45 | +end |
| 46 | + |
| 47 | +-- Returns the node's children |
| 48 | +function tree:children(node) |
| 49 | + return node.children |
| 50 | +end |
| 51 | + |
| 52 | +return tree |
0 commit comments