---
title: "二叉排序树"
author: "ArronZhen"
date: "2012-10-29T08:46:54Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-10-29T08:46:54Z"
id: 1707077
url: "https://arronzhen.iteye.com/blog/1707077"
---

### [学习“五大经典查找”(3)](http://128kj.iteye.com/blog/1683389)

- **博客分类：**
- [查找](http://128kj.iteye.com/category/248049)

[java](http://www.iteye.com/blogs/tag/java) [数据结构](http://www.iteye.com/blogs/tag/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84) [算法](http://www.iteye.com/blogs/tag/%E7%AE%97%E6%B3%95)  

今天就聊聊这个”五大经典查找“中的最后一个”二叉排序树“，又叫二叉查找树。

1\. 概念  
![](http://dl.iteye.com/upload/attachment/0074/1780/5467852b-afdc-3345-812f-4ccd19e6df72.gif)

如图就是一棵二叉排序树:  
![](http://dl.iteye.com/upload/attachment/0074/1782/cf1653ae-24bc-3b94-a5ef-44f6f01b7514.png)

2.实际操作：

    我们都知道，对一个东西进行操作，无非就是增删查改，接下来我们就聊聊其中的基本操作。

    &lt;1&gt; 插入：相信大家对“排序树”的概念都清楚了吧，那么插入的原理就很简单了。  
比如说我们插入一个20到这棵树中。

首先：20跟50比，发现20是老小，不得已，得要归结到50的左子树中去比较。  
然后：20跟30比，发现20还是老小。  
再然后：20跟10比，发现自己是老大，随即插入到10的右子树中。  
最后： 效果呈现图如下：

![](http://dl.iteye.com/upload/attachment/0074/1784/6dec9257-149c-363a-91db-38ce75b592c3.png)

&lt;2&gt;查找：相信懂得了插入，查找就跟容易理解了。

就拿上面一幅图来说，比如我想找到节点10.

首先：10跟50比，发现10是老小，则在50的左子树中找。  
然后：10跟30比，发现还是老小，则在30的左子树中找。  
再然后:  10跟10比，发现一样，然后就返回找到的信号。  
          
&lt;3&gt;删除：删除节点在树中还是比较麻烦的，主要有三种情况。

《1》 删除的是“叶节点20“，这种情况还是比较简单的，删除20不会破坏树的结构。如图：

![](http://dl.iteye.com/upload/attachment/0074/1786/6b8d962d-2502-3233-9272-07815f22db8f.png)

《2》删除”单孩子节点90“，这个情况相比第一种要麻烦一点点，需要把他的孩子顶上去。  
![](http://dl.iteye.com/upload/attachment/0074/1788/64e59969-1da2-38fd-bcc9-7f7eb138d2f0.png)

《3》删除“左右孩子都有的节点50”，这个让我在代码编写上纠结了好长时间，问题很直白，我把50删掉了，谁顶上去了问题，是左孩子呢？还是右 孩子呢？还是另有蹊跷？这里我就坦白吧，不知道大家可否知道“二叉树”的中序遍历，现在可以当公式记住吧，就是找到右节点的左子树最左孩子。

比如：首先 找到50的右孩子70。  
然后  找到70的最左孩子，发现没有，则返回自己。  
最后  原始图和最终图如下。

![](http://dl.iteye.com/upload/attachment/0074/1790/150f56c8-affc-3538-9411-286be597b8d1.png)

![](http://dl.iteye.com/upload/attachment/0074/1792/60aed79d-ae00-33eb-a908-72646f26ee1e.png)

3.说了这么多，上代码说话。

Java代码  [![收藏代码](http://128kj.iteye.com/images/icon_star.png)]()

001. //二叉搜索树
002. public   class  BinarySearchTree&lt;T  extends  Comparable&lt;?  super  T&gt;&gt;
003. {
004. /\** 二叉排序树的根 \*/
005. private  BinaryNode&lt;T&gt; root;
006. /\**
007. * 构造一棵空树.
008. \*/
009. public  BinarySearchTree( )
010. {
011. root = null ;
012. }
013. /\**
014. * 在二叉搜索树中插入数据.
015. * @param x the item to insert.
016. \*/
017. public   void  insert( T x )
018. {
019. root = insert( x, root );
020. }
021. /\**
022. * 从二叉搜索中删除数据（节点）.
023. * @param x the item to remove.
024. \*/
025. public   void  remove( T x )
026. {
027. root = remove( x, root );
028. }
029. /\**
030. * 找最小数据.
031. * @return smallest item or null if empty.
032. \*/
033. public  T findMin( )
034. {
035. if ( isEmpty( ) )
036. throw   new  UnderflowException( );
037. return  findMin( root ).element;
038. }
039. /\**
040. * 找最大数据.
041. * @return the largest item of null if empty.
042. \*/
043. public  T findMax( )
044. {
045. if ( isEmpty( ) )
046. throw   new  UnderflowException( );
047. return  findMax( root ).element;
048. }
049. //二叉搜索树中是否包含x
050. public   boolean  contains( T x )
051. {
052. return  contains( x, root );
053. }
054. public   void  makeEmpty( )
055. {
056. root = null ;
057. }
058. public   boolean  isEmpty( )
059. {
060. return  root ==  null ;
061. }
062. //中序遍历输出二叉搜索树的内容
063. public   void  printTree( )
064. {
065. if ( isEmpty( ) )
066. System.out.println( "Empty tree"  );
067. else
068. printTree( root );
069. }
070. //插入
071. private  BinaryNode&lt;T&gt; insert( T x, BinaryNode&lt;T&gt; t )
072. {
073. if ( t ==  null  )
074. return   new  BinaryNode&lt;T&gt;( x,  null ,  null  );
075. int  compareResult = x.compareTo( t.element );
076. if ( compareResult &lt;  0  )
077. t.left = insert( x, t.left );
078. else   if ( compareResult &gt;  0  )
079. t.right = insert( x, t.right );
080. else
081. ;  // 重复的,什么也不做。当然你也可以将重复的数据加入右边。
082. return  t;
083. }
084. //删除
085. private  BinaryNode&lt;T&gt; remove( T x, BinaryNode&lt;T&gt; t )
086. {
087. //先在树中查找x
088. if ( t ==  null  )
089. return  t;    // 没有找到，返回
090. int  compareResult = x.compareTo( t.element );
091. // 在左树中找
092. if ( compareResult &lt;  0  )
093. t.left = remove( x, t.left );
094. //在右树中找
095. else   if ( compareResult &gt;  0  )
096. t.right = remove( x, t.right );
097. //在树中找到了节点值为x的节点
098. else   if ( t.left !=  null  && t.right !=  null  )  // 这个节点有两个孩子节点
099. {
100. t.element = findMin( t.right ).element;
101. t.right = remove( t.element, t.right );
102. }
103. else //这个节点只有一个孩子节点或没有孩子节点
104. t = ( t.left != null  ) ? t.left : t.right;
105. return  t;
106. }
107. //在二叉搜索树中找最小值节点
108. private  BinaryNode&lt;T&gt; findMin( BinaryNode&lt;T&gt; t )
109. {
110. if ( t ==  null  )
111. return   null ;
112. else   if ( t.left ==  null  )
113. return  t;
114. return  findMin( t.left );
115. }
116. //在二叉搜索树中找最大值节点
117. private  BinaryNode&lt;T&gt; findMax( BinaryNode&lt;T&gt; t )
118. {
119. if ( t !=  null  )
120. while ( t.right !=  null  )
121. t = t.right;
122. return  t;
123. }
124. //是否包含
125. private   boolean  contains( T x, BinaryNode&lt;T&gt; t )
126. {
127. if ( t ==  null  )
128. return   false ;
129. int  compareResult = x.compareTo( t.element );
130. if ( compareResult &lt;  0  )
131. return  contains( x, t.left );
132. else   if ( compareResult &gt;  0  )
133. return  contains( x, t.right );
134. else
135. return   true ;     // Match
136. }
137. //中序遍历二叉树
138. private   void  printTree( BinaryNode&lt;T&gt; t )
139. {
140. if ( t !=  null  )
141. {
142. printTree( t.left );
143. System.out.print(t.element+"  " );
144. printTree( t.right );
145. }
146. }
147. // 二叉搜索树节点
148. private   static   class  BinaryNode&lt;T&gt;
149. {
150. // Constructors
151. BinaryNode( T theElement )
152. {
153. this ( theElement,  null ,  null  );
154. }
155. BinaryNode( T theElement, BinaryNode&lt;T&gt; lt, BinaryNode&lt;T&gt; rt )
156. {
157. element  = theElement;
158. left     = lt;
159. right    = rt;
160. }
161. T element;            // The data in the node
162. BinaryNode&lt;T&gt; left;   // Left child
163. BinaryNode&lt;T&gt; right;  // Right child
164. }
165. // 测试
166. public   static   void  main( String \[ ] args )
167. {
168. //创建二叉排序树
169. int  list\[]={  50 ,  30 ,  70 ,  10 ,  40 ,  90 ,  80 };
170. BinarySearchTree&lt;Integer&gt; bsTree = new  BinarySearchTree&lt;Integer&gt;( );
171. for (  int  i =  0 ; i&lt;list.length;i++)
172. bsTree.insert( list\[i] );
173. System.out.println("中序遍历的原始数据：" );
174. //中序遍历
175. bsTree.printTree( );
176. System.out.printf("\\n--------------------------------" );
177. //查找一个节点
178. System.out.printf("\\n10在二叉树中是否包含："  + bsTree.contains( new  Integer( 10 )));
179. System.out.printf("\\n---------------------------------" );
180. //插入一个节点
181. bsTree.insert(20 );
182. System.out.printf("\\n20插入到二叉树，中序遍历后：" );
183. //中序遍历
184. bsTree.printTree();
185. System.out.printf("\\n-----------------------------------\\n" );
186. System.out.printf("删除叶子节点 20， \\n中序遍历后：" );
187. //删除一个节点(叶子节点)
188. bsTree.remove(new  Integer( 20 ));
189. //再次中序遍历
190. bsTree.printTree();
191. System.out.printf("\\n\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\\n" );
192. System.out.printf("删除单孩子节点 90， \\n中序遍历后：" );
193. //删除单孩子节点
194. bsTree.remove(new  Integer( 90 ));
195. //再次中序遍历
196. bsTree.printTree();
197. System.out.printf("\\n\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\\n" );
198. System.out.printf("删除根节点 50， \\n中序遍历后：" );
199. //删除根节点
200. bsTree.remove(new  Integer( 50 ));
201. bsTree.printTree();
202. }
203. }
204. public   class  UnderflowException  extends  RuntimeException{}

运行结果：

D:\\java&gt;java   BinarySearchTree  
中序遍历的原始数据：  
10  30  40  50  70  80  90  
\------------------------------------------------  
10在二叉树中是否包含：true  
\--------------------------------------------------  
20插入到二叉树，中序遍历后：10  20  30  40  50  70  80  90  
\-------------------------------------------------  
删除叶子节点 20，  
中序遍历后：10  30  40  50  70  80  90  
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**  
删除单孩子节点 90，  
中序遍历后：10  30  40  50  70  80  
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**  
删除根节点 50，  
中序遍历后：10  30  40  70  80

值的注意的是：二叉排序树同样采用“空间换时间”的做法。

突然发现，二叉排序树的中序遍历同样可以排序数组，呵呵，不错！

PS:  插入操作：O(LogN)。

       删除操作：O(LogN)。

       查找操作：O(LogN）。