<span style="font-family:微軟雅黑;">
</span>
<span style="font-family: 微軟雅黑; ">二叉樹的操作一般可以分爲:遍歷,查找、插入、刪除</span>
/**
* 中序遍歷:
* 1、調用自身來遍歷節點的左子樹
* 2、訪問這個節點
* 3、調用自身來遍歷節點的右子樹
* @param root
*/
public void prevTree(Node root){
if(root!=null){
prevTree(root.leftChild);
System.out.println(root.iData+" ");
prevTree(root.rightChild);
}
}
//最左子樹爲最小值
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 查找最大值
//最右子樹爲最大值
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 尋找特定節點
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;
}