Skip to content

Instantly share code, notes, and snippets.

@umarsheikh umarsheikh/node.rb
Created Nov 7, 2017

Embed
What would you like to do?
class Node
attr_accessor :left, :right, :depth, :name
def initialize(depth, name)
@depth = depth
@name = name
end
end
def traverse(node, k, depth=0)
return if k < 0
return if depth > k
if depth == k
puts node.inspect
elsif depth < k
if node.left
traverse(node.left, k, depth+1)
end
if node.right
traverse(node.right, k, depth+1)
end
end
end
def testrunner
n = Node.new(0, 'zero')
##
n.left = Node.new(1, 'l-1')
n.right = Node.new(1, 'r-1')
##
n.left.left = Node.new(2, 'l-l')
n.left.right = Node.new(2, 'l-r')
n.right.left = Node.new(2, 'r-l')
n.right.right = Node.new(2, 'r-r')
##
n.left.left.left = Node.new(3, 'l-l-l')
n.left.left.right = Node.new(3, 'l-l-r')
n.left.right.left = Node.new(3, 'l-r-l')
n.left.right.right = Node.new(3, 'l-r-l')
n.right.left.left = Node.new(3, 'r-l-l')
n.right.left.right = Node.new(3, 'r-l-r')
n.right.right.left = Node.new(3, 'r-r-l')
n.right.right.right = Node.new(3, 'r-r-r')
##
traverse(n, 3, 0)
traverse(n, 2, 0)
traverse(n, 1, 0)
traverse(n, 0, 0)
end
testrunner
@umarsheikh

This comment has been minimized.

Copy link
Owner Author

commented Nov 7, 2017

Ruby Code to Print All Nodes in a Tree at Depth [k]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.