二叉樹系列之二(遍歷與查找)

<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、查找分爲找最小值、最大值和需找特定的值
由二叉搜索樹的性質(左小右大)知:二叉樹中最左邊的節點爲最小值,最右邊的節點爲最大值

2.1 查找最小值
     
    節點一直往左邊移動,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;
		
	}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章