Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. # We would use a binary tree to implement Breadth First Search(BFS)
  2. # We could use a shift or push to add a remove from an array or
  3. # we use queue to help implement BFS, we use "deq" to remove an node and "enq" to add node
  4. # 1. Add root node to the queue, and mark it as visited.
  5. # 2. Loop on the queue as long as it's not empty.
  6. # 1. Get and remove the node at the top of the queue(current).
  7. # 2. For every non-visited child of the current node, do the following:
  8. # 1. Mark it as visited.
  9. # 2. Check if it's destination node, If so, then return it.
  10. # 3. Otherwise, push it to the queue.
  11. # 3. If queue is empty, then destination node was not found!
  12.  
  13. class BinaryTree
  14. attr_accessor :value, :left, :right
  15.  
  16. def initialize(value)
  17. @value = value
  18. @left = nil
  19. @right = nil
  20. end
  21.  
  22. # use this method to build the binary tree
  23. # This method inside children node to the left of a node
  24. def insert_left(value)
  25. if self.left.nil?
  26. self.left = BinaryTree.new(value)
  27. else
  28. new_node = BinaryTree.new(value)
  29. new_node.left = self.left
  30. self.left = new_node
  31. end
  32. end
  33.  
  34. # use this method to build the binary tree
  35. # This method inside children node to the right of a node
  36. def insert_right(value)
  37. if self.right.nil?
  38. self.right = BinaryTree.new(value)
  39. else
  40. new_node = BinaryTree.new(value)
  41. new_node.right = self.right
  42. self.right = new_node
  43. end
  44. end
  45. end
  46.  
  47. def bread_first_search(node)
  48. queue = Queue.new
  49. queue.enq(node) # enqueue origin node
  50. visited = []
  51.  
  52. while !queue.empty?
  53. current_node = queue.deq
  54. visited << current_node # make current node as visited
  55.  
  56. if current_node.value == node.value
  57. return current_node . # return node if is the destination node
  58. end
  59.  
  60. if current_node.left && !visited.include?(current_node.left)
  61. queue.enq(current_node.left) #enqueue the node to the left of the current node
  62. end
  63.  
  64. if current_node.right && !visited.include?(current_node.right)
  65. queue.enq(current_node.right) #enqueue the node to the right of the current node
  66. end
  67. end
  68. end
  69.  
  70. ### Create a binary tree
  71. a_node = BinaryTree.new('a')
  72. a_node.insert_left('b')
  73. a_node.insert_right('c')
  74.  
  75. b_node = a_node.left
  76. b_node.insert_right('d')
  77.  
  78. c_node = a_node.right
  79. c_node.insert_left('e')
  80. c_node.insert_right('f')
  81.  
  82. e_node = c_node.left
  83. f_node = c_node.right
  84.  
  85. p bread_first_search(a_node)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement