Created
June 26, 2018 02:16
-
-
Save cefaijustin/045e43bdabe9432fb78cca0e12a67a49 to your computer and use it in GitHub Desktop.
Binary Tree Traversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BinaryTree | |
attr_accessor :payload, :left, :right | |
def initialize(payload, left, right) | |
@payload = payload | |
@left = left | |
@right = right | |
end | |
def self.build_tree(array) | |
nodes = [] | |
array.each_with_index do |payload, index| | |
tree = BinaryTree.new(payload, nil, nil) | |
if payload != nil && index != nil && array[index + 1] > array[0] | |
tree.right = array[index + 1] | |
payload = tree.right | |
end | |
if payload != nil && index != nil && array[index + 1] < array[0] | |
tree.left = array[index + 1] | |
payload = tree.left | |
end | |
end | |
end | |
# nodes[0].payload is the value of the trunk (7) | |
# tree.payload is the value of the rest of the items in the array | |
# tree.left = some node that is less than the current payload | |
# tree.right = some node that is greater than current payload | |
def flatten_tree | |
end | |
end | |
# build tree is going to take array below and build a structure of nodes | |
# connected to nodes etc. | |
# flatten is going to be called on a tree (node) and will output an | |
# array that is in the sorted order | |
array = [7, 4, 9, 1, 6, 14, 10] | |
tree = BinaryTree.build_tree(array) | |
# p tree.flatten_tree | |
# build up the tree | |
# ten = BinaryTree.new(10, nil, nil) | |
# fourteen = BinaryTree.new(14, ten, nil) | |
# nine = BinaryTree.new(9, nil, fourteen) | |
# six = BinaryTree.new(6, nil, nil) | |
# one = BinaryTree.new(1, nil, nil) | |
# four = BinaryTree.new(4, one, six) | |
# trunk = BinaryTree.new(7, four, nine) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment