<span style="font-family:微软雅黑;">
</span>
<span style="font-family: 微软雅黑; ">二叉树的操作一般可以分为:遍历,查找、插入、删除</span>
如无特别说明,此处的二叉树均指搜索二叉树。
二叉搜索树的性质:节点的值不小于左子节点的值,但又不大于右子节点的值。(左小,右大)
1、遍历分为中序遍历(升序)、先序遍历和后序遍历
一般采用递归的方法:
<1>、调用自身来遍历节点的左子树
<2>、访问这个节点
<3>、调用自身来遍历节点的右子树
代码:
/**
* 中序遍历:
* 1、调用自身来遍历节点的左子树
* 2、访问这个节点
* 3、调用自身来遍历节点的右子树
* @param root
*/
public void prevTree(Node root){
if(root!=null){
prevTree(root.leftChild);
System.out.println(root.iData+" ");
prevTree(root.rightChild);
}
}
2、查找分为找最小值、最大值和需找特定的值
由二叉搜索树的性质(左小右大)知:二叉树中最左边的节点为最小值,最右边的节点为最大值
节点一直往左边移动,curretnt = current.leftChild;
//最左子树为最小值
public void findMin(){
Node current =root;
Node last=null;
while(current!=null){
last = current;
current = current.leftChild;
}
System.out.print("Min:");
display(last);
}
2.2 查找最大值
节点一直往右边移动,curretnt = current.rightChild;
//最右子树为最大值
public void findMax(){
Node current =root;
Node last=null;
while(current!=null){
last = current;
current = current.rightChild;
}
System.out.print("Max:");
display(last);
}
2.3 寻找特定节点
只要current节点值不等于关键值,则循环进行;关键值小于节点值,表明关键值可能位于该节点的左子树;否则表明关键值可能位于该节点的右子树;若节点为空,则表明没有搜索到,直接退出;否则只有当节点值跟关键值相等才能退出循环。
三种实现方法
public void find(int key){
Node current=root;
while(current.iData!=key){
if(current.iData<key){
current = current.rightChild;
}else{
current = current.leftChild;
}
if(current==null){
System.out.println("can not find "+key);
return;
}
}
System.out.println("found,the key fDouble is "+current.fDouble);
<span style="font-family: 微软雅黑; line-height: 1.5; "> }</span>
/**
* 最为简洁写法
* @param key
* @param nRoot
* @return
*/
public Node find(int key ,Node nRoot){
if(nRoot==null){
nRoot = root;
}
while(nRoot!=null){
if(nRoot.iData>key){
nRoot=nRoot.leftChild;
}else if(nRoot.iData<key){
nRoot=nRoot.rightChild;
}else {
return nRoot;
}
}
return null;
}
//递归调用
public Node findNode(int key ,Node nRoot){
if(nRoot==null){
return null;
}
if(nRoot.iData==key)
return nRoot;
else if(nRoot.iData>key){
return find(key, nRoot.leftChild);
}else {
return find(key, nRoot.rightChild);
}
}
3.插入
叉树插入节点的位置只能是叶子节点或叶子节点的父节点的左子树或右子树,关键就是要找到该叶子节点或父节点。
如果找到了适合的父节点。若待插入节点的值大于父节点的值,则待插入节点作为父节点的右子树;若待插入节点的值小于父节点的值,则待插入节点作为父节点的左子树。
</pre><pre name="code" class="java">/**
* 找到跟待插入节点的位置,记录其父节点
* @param e
*/
public void insert (Node e){
if(root==null){
root = e;
return ;
}
Node t = root;
Node parent =null;
/**
* 找插入位置的父节点的最佳方法(底层源码采用的方法)
*/
while(t!=null){
parent = t;
if(t.iData>e.iData)
t = t.leftChild;
else if(t.iData<e.iData)
t = t.rightChild;
}
if(parent.iData>e.iData)
parent.leftChild = e;
else
parent.rightChild = e;
}