ruby tree_search_attempt.rb

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby tree_search_attempt.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
	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

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

Ruby运算符

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

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

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

什么是ruby?

ruby和ruby ee