Created
December 3, 2013 23:45
-
-
Save OfTheDelmer/7779811 to your computer and use it in GitHub Desktop.
Lecture on BFS
This file contains hidden or 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 BinTree | |
| attr_accessor :left, :right, :val | |
| def initialize(val) | |
| @left = nil | |
| @right = nil | |
| @val = val | |
| end | |
| def insert_node(new_val) | |
| if new_val < @val | |
| if(@left == nil) | |
| @left = BinTree.new(new_val) | |
| else | |
| @left.insert_node(new_val) | |
| end | |
| elsif(new_val > @val) | |
| if(@right == nil) | |
| @right = BinTree.new(new_val) | |
| else | |
| @right.insert_node(new_val) | |
| end | |
| end | |
| end | |
| # Searching the Tree for search_val | |
| def search_tree(search_val) | |
| # Start our queue and Visited list | |
| queue = Queue.new | |
| visited = [] | |
| # adds root tree to queue | |
| # adds to visited list | |
| queue.enq(self) | |
| visited.push(self) | |
| while !queue.empty? | |
| current_node = queue.deq | |
| # Check if current_node val == search_val | |
| if current_node.val == search_val | |
| return current_node | |
| end | |
| if current_node.left && !visited.include?(current_node.left) | |
| queue.enq(current_node.left) | |
| visited.push(current_node.left) | |
| end | |
| if current_node.right && !visited.include?(current_node.right) | |
| queue.enq(current_node.right) | |
| visited.push(current_node.right) | |
| end | |
| end | |
| "none!" | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment