I am recursively creating a balanced binary search tree in Ruby using a sorted array. However, I'm having trouble at the ending return value. Instead of all the nodes bubbling up, creating a tree and returning the base level 1 node, the very last node at the bottom of the tree is returned.
It doesn't seem like the nodes being created are linked together at all (printing the instantiated class using p list
only returns the last node). How do I link the nodes together and return the level 1 root node?
Code:
class Node include Comparable attr_accessor :value, :left, :right def initialize(value, left = nil, right = nil) @value = value @left = left @right = right end end class Tree attr_accessor :sorted_arr, :arr def initialize(arr) @arr = arr @sorted_arr = arr.sort.uniq end #Problem: nodes not being linked together def build_tree(arr, start, last) if start > last return nil end mid_index = (start + last) / 2 @root = Node.new(arr[mid_index]) @root.left = build_tree(arr, start, mid_index - 1) @root.right = build_tree(arr, mid_index + 1, last) return @root end end list = Tree.new([1, 7, 4, 23, 8, 9, 4, 3, 6, 7, 9, 67, 6345, 324]) list.build_tree(list.sorted_arr, 0, list.sorted_arr.length-1) p list
https://stackoverflow.com/questions/67308470/returning-level-1-node-in-a-balanced-binary-search-tree-ruby April 29, 2021 at 05:59AM
没有评论:
发表评论