ruby bfs_and_trees.rb

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby bfs_and_trees.rb相关的知识,希望对你有一定的参考价值。


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




以上是关于ruby bfs_and_trees.rb的主要内容,如果未能解决你的问题,请参考以下文章

Ruby运算符

Ruby 25 岁了!Ruby 之父说 Ruby 3 有望 3 倍提速

如何学习ruby?Ruby学习技巧分享

ruby Ruby脚本,看看是否用openssl编译了ruby

什么是ruby?

ruby和ruby ee