在一顆二叉樹上插入節點

在一顆二叉樹上插入節點,插入是建立在小於父節點,則插入到父節點左邊,如果大於父節點,則插入到父節點右邊。在插入樹節點,需要判斷樹根是否爲空,如果不爲空,則需要當前節點指向樹根和父節點指向當前節點。直到當前節點等於null,那麼可以在父節點左邊或者右邊插入新節點,並且返回樹根跳出循環。如果樹根爲空,直接把樹根指向新創建的節點,實現過程如下所示:

package cn.edu.nwu.structs.tree;

/**
 * @author jcm
 * 插入樹節點
 *時間 2016年9月2日
 */
public class InsertBinaryTreeNode {
	public static void main(String[] args) {
		BinaryTreeNode root = null;
		root = insertBinaryTNode(root,43);
		root = insertBinaryTNode(root,87);
		root = insertBinaryTNode(root,-43);
		root = insertBinaryTNode(root,98);
		show(root,1);
	}
	/**
	 * @author jcm
	 *  在一顆二叉樹上插入節點,如果二叉樹爲空,就讓樹根指向新插入的節點
	 * @param root 樹根
	 * @param data 數據
	 * @return 返回樹根的節點
	 */
	public static BinaryTreeNode insertBinaryTNode(BinaryTreeNode root,int data){
		//創建樹節點
		BinaryTreeNode newTNode = new BinaryTreeNode(data);
		//如果樹根是空的,就讓樹根指向新創建的樹節點
		if(root == null){
			root = newTNode;
			return root;
		}else{
			//建立當前樹節點
			BinaryTreeNode currentTNode = root;
			while(true){
				//讓父節點指向當前節點
				BinaryTreeNode parentTNode = currentTNode;
				if(currentTNode.data > data){
					currentTNode = currentTNode.leftTreeNode;
					if(currentTNode == null){
						parentTNode.leftTreeNode = newTNode;
						return root;//跳出循環,並返回樹根
					}
				}else{
					currentTNode = currentTNode.rightTreeNode;
					if(currentTNode == null){
						parentTNode.rightTreeNode = newTNode;
						return root;
					}
				}
			}
		}
	}
	//中序遍歷,通過n控制層數
	public static void show(BinaryTreeNode root,int n){
		if(root == null){
			return ;
		}else{
			show(root.leftTreeNode,n+1);
			for (int i=0;i<n;i++){
				System.out.print("	");
			}
			System.out.println(root.data);
			show(root.rightTreeNode,n+1);
		}
	}
}


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