Created
December 4, 2013 00:19
-
-
Save OfTheDelmer/7780186 to your computer and use it in GitHub Desktop.
trees with many children and 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 but not the ideal search | |
| def search_bfs(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 | |
| #Better | |
| def search(val) | |
| if @val == val | |
| return self | |
| elsif @val > val && @left | |
| return @left.search(val) | |
| elsif @val < val && @right | |
| return @right.search(val) | |
| end | |
| return "Not Found!" | |
| end | |
| end | |
| class Tree | |
| attr_accessor :children, :val | |
| def initialize(val) | |
| @val = val | |
| @children = [] | |
| end | |
| def insert(val) | |
| @children.push(Tree.new(val)) | |
| end | |
| # Searching the Tree for search_val | |
| def search_bfs(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 | |
| current_node.children.each do |child| | |
| if !visited.include?(child) | |
| queue.enq(child) | |
| visited.push(child) | |
| end | |
| end | |
| end | |
| "none!" | |
| end | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment