Posted 30 June 2016 - 02:34 PM
I have problems with stack overflow. I want to learn how to use recursive functions avoiding a stack overflow, if is posible. If not, I need help implementing a tree. In my code got a stack overflow when i try to create one, if has a big size(height). There is my attempt to make a tree.
Thanks in advance.
Node={}
function Node.new(n)
local self={}
local childrenL=nil
local childrenR=nil
local value=n
function self.addChildren(_n)
if _n<value then
if childrenL==nil then
childrenL=Node.new(_n)
else
childrenL.addChildren(_n)
end
else
if childrenR==nil then
childrenR=Node.new(_n)
else
childrenR.addChildren(_n)
end
end
end
function self.getValue()
return n
end
function self.dfs()
print(n)
os.sleep(0.05)
if childrenL~=nil then childrenL.dfs() end
os.sleep(0.05)
if childrenR~=nil then childrenR.dfs() end
end
return self
end
tree=Node.new(0)
for i=1, 500 do
tree.addChildren(i*-1)
print ("inserted child "..i*-1)
os.sleep(0)
end
tree.dfs()
Thanks in advance.