Last active
September 27, 2021 15:03
-
-
Save AlexAvlonitis/0c8bec315088c9dc249cd15c1723ebf7 to your computer and use it in GitHub Desktop.
BST tree traversals in ruby
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
# https://github.com/alexavlonitis | |
# BST Tree traversals in ruby, inorder, preorder and postorder using recursion | |
# Invert BST Tree in ruby using recursion | |
class Tree | |
attr_accessor :root | |
def initialize | |
@root = nil | |
end | |
def preorder(node = root) | |
return if node.nil? | |
puts node.value | |
preorder(node.left) | |
preorder(node.right) | |
end | |
def inorder(node = root) | |
return if node.nil? | |
inorder(node.left) | |
puts node.value | |
inorder(node.right) | |
end | |
def postorder(node = root) | |
return if node.nil? | |
postorder(node.left) | |
postorder(node.right) | |
puts node.value | |
end | |
def invert(node = root) | |
return if node.nil? | |
temp = node.left | |
node.left = node.right | |
node.right = temp | |
invert(node.left) | |
invert(node.right) | |
self | |
end | |
end | |
class Node | |
attr_accessor :value, :left, :right | |
def initialize(value) | |
@value = value | |
@left = nil | |
@right = nil | |
end | |
end | |
=begin | |
10 | |
/ \ | |
5 12 | |
/ \ | |
1 6 | |
Inverted | |
10 | |
/ \ | |
12 5 | |
/ \ | |
1 6 | |
=end | |
root = Node.new(10) | |
root.left = Node.new(5) | |
root.right = Node.new(12) | |
root.left.left = Node.new(1) | |
root.left.right = Node.new(6) | |
t = Tree.new | |
t.root = root | |
t.preorder | |
puts '###### Inverted ########' | |
inverted = t.invert | |
inverted.preorder |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment