Binary tree and recursion does my head in [solved]

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
togFox
Party member
Posts: 779
Joined: Sat Jan 30, 2021 9:46 am
Location: Brisbane, Oztralia

Binary tree and recursion does my head in [solved]

Post by togFox »

Binary tree - what super simple obvious thing am I overlooking? When I add node = 5, it works fine. When I then add node = 8, the new node '8' splats the 5 so that only the root is updated and the leafs are not.

Code: Select all

inspect = require 'lib.inspect'

local function insert(tree, node)
    if not next(tree) then
        tree = node
    elseif node.key <= tree.key then
        insert(node.left, node)
    elseif node.key > tree.key then
        insert(node.right, node)
    else
        error()
    end
    return tree
end

function love.load()

	local mytree = {}

    local datapoint = {}
    datapoint.key = 5
    datapoint.left = {}
    datapoint.right = {}
    mytree = insert(mytree, datapoint)

    datapoint.key = 8
    datapoint.left = {}
    datapoint.right = {}
    mytree = insert(mytree, datapoint)
	
	print(inspect(mytree))	-- prints to console
end
Last edited by togFox on Sun Jan 09, 2022 10:00 am, edited 1 time in total.
Current project:
https://togfox.itch.io/backyard-gridiron-manager
American football manager/sim game - build and manage a roster and win season after season
User avatar
togFox
Party member
Posts: 779
Joined: Sat Jan 30, 2021 9:46 am
Location: Brisbane, Oztralia

Re: Binary tree and recursion does my head in [solved]

Post by togFox »

Solution provided by zorg

Code: Select all

local function new(key)
    return {key = key, left = nil, right = nil} -- left and right are NOT empty tables, they don't exist at all.
end

local function insert(tree, node)
    if tree == nil then -- if the tree doesn't exist then set inserted node to be the root
        tree = node
    elseif node.key <= tree.key then
        if not tree.left then
            tree.left = node
        else
            insert(tree.left, node)
        end
    elseif node.key > tree.key then
        if not tree.right then
            tree.right = node
        else
            insert(tree.right, node)
        end
    end
    return tree
end

local test = new(5)
insert(test, new(8))
insert(test, new(3))
insert(test, new(4))

print(test.key)
print(test.left.key)
print(test.right.key)
print(test.left.right.key)
Current project:
https://togfox.itch.io/backyard-gridiron-manager
American football manager/sim game - build and manage a roster and win season after season
Post Reply

Who is online

Users browsing this forum: No registered users and 201 guests