-
Notifications
You must be signed in to change notification settings - Fork 0
/
day22_binary_search_trees.rb
66 lines (57 loc) · 1.45 KB
/
day22_binary_search_trees.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Node
attr_accessor :left,:right,:data
def initialize data
@left=@right=nil
@data=data
end
end
class Solution
def insert (root,data)
if root==nil
return Node.new(data)
else
if data<=root.data
cur=self.insert(root.left,data)
root.left=cur
else
cur=self.insert(root.right,data)
root.right=cur
end
end
return root
end
# Print each row of tree from left to right, from root to lowest row.
def levelOrder(root)
# Enqueue root node
if root != nil
queue = [root]
else
queue = []
end
# While queue is not empty / there are nodes to process
while queue != []
# Dequeue next node
node = queue.pop
# process tree's root / print the value of the node
print "#{node.data} "
# enqueue child elements from next level in order
# if tree has non-empty left subtree, enqueue left child
if node.left != nil
queue.insert(0,node.left)
end
# if tree has non-empty right subtree, enqueue right child
if node.right != nil
queue.insert(0,node.right)
end
end
end
end
# Provided by Hacker Rank:
myTree=Solution.new
root=nil
T=gets.to_i
for i in 1..T
data=gets.to_i
root=myTree.insert(root,data)
end
myTree.levelOrder(root)