- 浏览: 862384 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
yukang1:
蚂蚁lovejing 写道我也出现与楼上相同的问题。查了一些资 ...
Spring中实现文件上传 -
史玉凤:
必须用ie浏览器
javascript获取客户端网卡MAC地址和IP地址和计算机名 -
蚂蚁lovejing:
我也出现与楼上相同的问题。查了一些资料,描述的跟楼主的博文差不 ...
Spring中实现文件上传 -
温柔一刀:
djlijian 写道最近也在研究redis,如何在项目中使用 ...
Redis 常见的性能问题和解决方法 -
djlijian:
最近也在研究redis,如何在项目中使用呢?感觉网上的资料太少 ...
Redis 常见的性能问题和解决方法
I think that I shall never see
A poem as lovely as a tree...
"Trees," [Alfred] Joyce Kilmer
Trees in computer science are a relatively intuitive concept (except that they are usually drawn with the "root" at the top and the "leaves" at the bottom). This is because we are familiar with so many kinds of hierarchical data in everyday life, from the family tree to the corporate organization chart to the directory structures on our hard drives.
The terminology of trees is rich but easy to understand. Any item in a tree is a node; the first or topmost node is the root. A node may have descendants that are below it, and the immediate descendants are called children. Conversely, a node may also have a parent (only one) and ancestors. A node with no child nodes is called a leaf. A subtree consists of a node and all its descendants. To travel through a tree (for example, to print it out) is called traversing the tree.
We will look mostly at binary trees, though in practice a node can have any number of children. We will see how to create a tree, populate it, and traverse it; and we will look at a few real-life tasks that use trees.
We will mention here that in many languages such as C or Pascal, trees would be implemented using true address pointers. But in Ruby (as in Java, for instance), we don't use pointers; object references work just as well or better.
9.3.1. Implementing a Binary Tree
There is more than one way to implement a binary tree in Ruby. For example, we could use an array to store the values. Here we use a more traditional approach, coding much as we would in C, except that pointers are replaced with object references.
What is required to describe a binary tree? Well, each node needs an attribute of some kind for storing a piece of data. Each node also needs a pair of attributes for referring to the left and right subtrees under that node.
We also need a way to insert into the tree and a way of getting information out of the tree. A pair of methods will serve these purposes.
The first tree we'll look at implements these methods in a slightly unorthodox way. Then we will expand on the TRee class in later examples.
A tree is in a sense defined by its insertion algorithm and by how it is traversed. In this first example (see Listing 9.1), we define an insert method that inserts in a breadth-first fashionthat is, top to bottom and left to right. This guarantees that the tree grows in depth relatively slowly and that the tree is always balanced. Corresponding to the insert method, the traverse iterator will iterate over the tree in the same breadth-first order.
Listing 9.1. Breadth-First Insertion and Traversal in a Tree
class Tree attr_accessor :left attr_accessor :right attr_accessor :data def initialize(x=nil) @left = nil @right = nil @data = x end def insert(x) list = [] if @data == nil @data = x elsif @left == nil @left = Tree.new(x) elsif @right == nil @right = Tree.new(x) else list << @left list << @right loop do node = list.shift if node.left == nil node.insert(x) break else list << node.left end if node.right == nil node.insert(x) break else list << node.right end end end end def traverse() list = [] yield @data list << @left if @left != nil list << @right if @right != nil loop do break if list.empty? node = list.shift yield node.data list << node.left if node.left != nil list << node.right if node.right != nil enä end end items = [1, 2, 3, 4, 5, 6, 7] tree = Tree.new items.each {|x| tree.insert(x)} tree.traverse {|x| print "#{x} "} print "\n" # Prints "1 2 3 4 5 6 7 " |
This kind of tree, as defined by its insertion and traversal algorithms, is not especially interesting. It does serve as an introduction and something on which we can build.
9.3.2. Sorting Using a Binary Tree
For random data, a binary tree is a good way to sort. (Although in the case of already sorted data, it degenerates into a simple linked list.) The reason, of course, is that with each comparison, we are eliminating half the remaining alternatives as to where we should place a new node.
Although it might be fairly rare to do this nowadays, it can't hurt to know how to do it. The code in Listing 9.2 builds on the previous example.
Listing 9.2. Sorting with a Binary Tree
class Tree # Assumes definitions from # previous example... def insert(x) if @data == nil @data = x elsif x <= @data if @left == nil @left = Tree.new x else @left.insert x end else if @right == nil @right = Tree.new x else @right.insert x end end end def inorder() @left.inorder {|y| yield y} if @left != nil yield @data @right.inorder {|y| yield y} if @right != nil end def preorder() yield @data @left.preorder {|y| yield y} if @left != nil @right.preorder {|y| yield y} if @right != nil end def postorder() @left.postorder {|y| yield y} if @left != nil @right.postorder {|y| yield y} if @right != nil yield @data end end items = [50, 20, 80, 10, 30, 70, 90, 5, 14, 28, 41, 66, 75, 88, 96] tree = Tree.new items.each {|x| tree.insert(x)} tree.inorder {|x| print x, " "} print "\n" tree.preorder {|x| print x, " "} print "\n" tree.postorder {|x| print x, " "} print "\n" # Output: # 5 10 14 20 28 30 41 50 66 70 75 80 88 90 96 # 50 20 10 5 14 30 28 41 80 70 66 75 90 88 96 # 5 14 10 28 41 30 20 66 75 70 88 96 90 80 50 print "\n" |
9.3.3. Using a Binary Tree As a Lookup Table
Suppose we have a tree already sorted. Traditionally this has made a good lookup table; for example, a balanced tree of a million items would take no more than 20 comparisons (the depth of the tree or log base 2 of the number of nodes) to find a specific node. For this to be useful, we assume that the data for each node is not just a single value but has a key value and other information associated with it.
In most, if not all situations, a hash or even an external database table will be preferable. But we present this code to you anyhow:
class Tree # Assumes definitions # from previous example... def search(x) if self.data == x return self elsif x < self.data return left ? left.search(x) : nil else return right ? right.search(x) : nil end end end keys = [50, 20, 80, 10, 30, 70, 90, 5, 14, 28, 41, 66, 75, 88, 96] tree = Tree.new keys.each {|x| tree.insert(x)} s1 = tree.search(75) # Returns a reference to the node # containing 75... s2 = tree.search(100) # Returns nil (not found)
9.3.4. Converting a Tree to a String or Array
The same old tricks that allow us to traverse a tree will allow us to convert it to a string or array if we want. Here we assume an inorder traversal, though any other kind could be used:
class Tree # Assumes definitions from # previous example... def to_s "[" + if left then left.to_s + "," else "" end + data.inspect + if right then "," + right.to_s else "" end + "]" end def to_a temp = [] temp += left.to_a if left temp << data temp += right.to_a if right temp end end items = %w[bongo grimace monoid jewel plover nexus synergy] tree = Tree.new items.each {|x| tree.insert x} str = tree.to_a * "," # str is now "bongo,grimace,jewel,monoid,nexus,plover,synergy" arr = tree.to_a # arr is now: # ["bongo",["grimace",[["jewel"],"monoid",[["nexus"],"plover", # ["synergy"]]]]]
Note that the resulting array is as deeply nested as the depth of the tree from which it came. You can, of course, use flatten to produce a non-nested array.
发表评论
-
Query
2008-01-31 17:39 48class System::FastQuery de ... -
Fast Query
2008-01-19 15:07 4028class System::FastQuery def s ... -
9.2. Working with Stacks and Queues
2008-01-19 15:04 3753Stacks and queues are the first ... -
9.1. Working with Sets
2008-01-19 15:03 3376We've already seen how certain ... -
8.3. Enumerables in General
2008-01-19 14:26 3520What makes a collection enumera ... -
8.2. Working with Hashes
2008-01-19 14:25 3770Hashes are known in some circle ... -
计算两个字符串之间的Levenshtein距离
2008-01-09 23:32 5211Levenshtein距离 class String ... -
字符串的编码和解码
2008-01-09 23:11 3831rot13编码和解码 class String def r ... -
rails应用自动化部署——使用capistrano2.0
2007-10-10 18:59 6293昨天用capistrano2.0把应用部署搞的比较自动化了一点 ... -
selenium和ajax的测试问题
2007-08-13 15:51 6626Hi,all I am having doubts in se ... -
在selenium测试中使用ActiveRecord
2007-08-10 18:15 5140ActiveRecord是rails的框架,我们在seleni ... -
关于rails应用的验收测试
2007-08-08 18:26 4766ruby的测试运行的本来都慢,selenium的验收测试跑起来 ... -
Exception: Bad file descriptor - connect(2)
2007-08-07 15:59 5489Hi,all I am trying to test web ...
相关推荐
《Tina90-TI_zh.9.3.150.328安装包:深入了解Tina软件的应用与安装》 Tina90-TI_zh.9.3.150.328是一款针对电子工程师设计的专业仿真软件,由Texas Instruments(TI)公司开发,旨在为用户提供一个强大的电路分析和...
scrt-x64-bsafe.9.3.0.2905.exe
AltiumDesignerSummer9Build9.3.1.19182Crack.rar
UltraISOV9.3.6.2766 免注册版
539058961669292AutoJsPro9_Pro 9.3.11-0.apk
破解AD09的压缩包仅适用于Build 9.3.1.19182 2.破解已去除标题上的Not signed in 3.局域网内用同一license不再提示冲突 4.仅供学习研究使用,勿用于非法用途。
pdi-ce-9.3.0.0-428.zip Kettle
标题 "pdi-ce-9.3.0.0-428a安装包-1(kettle)" 提供的信息表明这是一个关于Pentaho Data Integration(PDI)的社区版(CE)9.3.0.0-428a的安装包。Kettle是PDI的别名,它是一个强大的ETL(Extract, Transform, Load...
在安装SecureCRT9.3.0.2905时,通常会包含两个执行文件scrt-sfx-x64-bsafe.9.3.0.2905.exe和scrt-sfx-x86-bsafe.9.3.0.2905.exe,分别对应64位和32位的Windows系统。确保选择适合自己系统版本的安装文件。"有问题点...
Altium Designer Summer 9(9.3.1.19182)的安装步骤和图解
scrt-sfx-x64-bsafe.9.3.2.2978.exe
MacDrive_Pro_9.3.2.6 读取MAC分区
赠送jar包:jetty-security-9.3.19.v20170502.jar; 赠送原API文档:jetty-security-9.3.19.v20170502-javadoc.jar; 赠送源代码:jetty-security-9.3.19.v20170502-sources.jar; 赠送Maven依赖信息文件:jetty-...
赠送jar包:jetty-webapp-9.3.19.v20170502.jar; 赠送原API文档:jetty-webapp-9.3.19.v20170502-javadoc.jar; 赠送源代码:jetty-webapp-9.3.19.v20170502-sources.jar; 赠送Maven依赖信息文件:jetty-webapp-...
赠送jar包:jetty-servlet-9.3.19.v20170502.jar; 赠送原API文档:jetty-servlet-9.3.19.v20170502-javadoc.jar; 赠送源代码:jetty-servlet-9.3.19.v20170502-sources.jar; 赠送Maven依赖信息文件:jetty-...
scrt-sfx-x64-bsafe.9.3.1.2929.exe
《 UltraISO 9.3.0.2610:全方位刻录与镜像处理专家》 UltraISO,全称“UltraISO Premium”,是一款全球知名的光盘映像文件处理工具,由EzB Systems公司开发。它以其强大的功能、易用的界面以及全面的刻录支持,...
scrt-x64-bsafe.9.3.2.2978.exe
该资源是福昕高级PDF编辑器企业版v9.3.0.10826的破解补丁。软件安装包可以去官网下载,网址是:https://www.foxitsoftware.cn/downloads/,资源里面包含有破解步骤说明的txt文件。 资源上传时间:2018-10.16 【温馨...