<pre name="code" class="plain">PG.lua文件 -- 这个用来输出处理 打log
PG = {}
function PG.Log(str)
print(str);
end
首先是pinghengtree.lua文件 数据结构定义在这里
require "PG";
_M = {};
rawset(_M,"pinghengtree",{});
local pinghengtree = rawget(_M,"pinghengtree");
-- pinghengtree = {};
pinghengtree.tree = {};
local tree = pinghengtree.tree;
function tree: new(lefttree,righttree,data)
local o = {};
o.data = data;
o.lefttree = lefttree;
o.righttree = righttree;
setmetatable(o,self);
self.__index = self;
return o;
end
function tree:AddChild(direction,data)
PG.Log(direction);
if direction == "left" then
PG.Log(" exe this?")
if self.lefttree == nil then
PG.Log("self's leftnode is nil ")
self.lefttree = self:new(nil,nil,data);
else
self.lefttree.data = data;
end
elseif direction == "right" then
if self.righttree == nil then
self.righttree = self:new(nil,nil,data);
PG.Log("self's rightnode is nil ")
else
self.righttree.data = data;
end
end
end
function pinghengtree.FindRoot(rt,data)
if rt == nil then
return nil;
end
if rt.data == data then
return rt;
else
local t = nill;
t = pinghengtree.FindRoot(rt.lefttree,data)
if t ~= nil then
return t;
end
t = pinghengtree.FindRoot(rt.righttree,data)
if t ~= nil then
return t;
end
return nil;
end
end
function pinghengtree.CreateNode(rt,data)
if rt.data < data then
if rt.righttree ~= nil then
return pinghengtree.CreateNode(rt.righttree,data);
else
local tree = pinghengtree.Class();
rt.righttree= tree:new(nil,nil,data);
return rt.righttree;
end
end
if rt.data == data then
return rt;
end
if rt.data > data then
if rt.lefttree ~= nil then
return pinghengtree.CreateNode(rt.lefttree,data);
else
local tree = pinghengtree.Class();
rt.lefttree = tree:new(nil,nil,data);
return rt.lefttree;
end
end
end
local datali= {1,3,5,7,2,4,6,8,9,10};
function pinghengtree.Class()
return tree;
end
function pinghengtree.PrintTree(rt)
if rt ~= nil then
PG.Log(rt.data);
end
if rt.lefttree~= nil then
pinghengtree.PrintTree(rt.lefttree);
end
if rt.righttree~= nil then
pinghengtree.PrintTree(rt.righttree);
end
end
function pinghengtree.CreateTree(rt,datalist) -- dt is data list
for i = 2,#datalist do
pinghengtree.CreateNode(rt,datalist[i]);
end
end
-- pinghengtree.Test = function( )
-- print("tet");
-- end
function pinghengtree.Test()
print("tet");
end
最后是main.lua文件<pre name="code" class="plain">local datalist = {1,3,5,7,2,4,6,8,9,10};
local tree = treeRoot:new(nil,nil,datalist[1]);
pinghengtree.CreateTree(tree,datalist);
for i = 1,10 do
local newRoot = pinghengtree.FindRoot(tree,i);
PG.Log(newRoot.data);
end
pinghengtree.PrintTree(tree);
--后续会加入新的内容 为什么用lua来实现 lua简单啊 不像c++ 内存处理 指针 繁杂的语法就是大大的障碍 还是脚本比较容易表达思想 改成c++也容易