Java實現二叉樹添加、二叉排序樹、中序遍歷

實現要求:

設計二叉樹類(BinaryTree),該類內部使用二叉樹結構存放二叉樹節點 (BinaryTreeNode),每個節點可存放一個整數值。
 該二叉樹類提供方法進行節點的追加(追加節點時,構建二叉排序樹),並提 供中序遍歷二叉樹節點的方法。

分析:

隨機生成部分整數值{10,3,20,7,5,33,27,100,0}

以上整數值,生成二叉排序樹應如下:

不同排序方式,排序結果應爲:

先序排列:根--左--右,10,3,0,7,5,20,33,27,100

中序排列:左--根--右,0,3,5,7,10,20,27,33,100(二叉排序樹的中序遍歷,爲升序排列)

後序排列:左--右--根,0,5,7,3,27,100,33,20,10

BinaryTreeNode類(已省略getter和setter方法):

public class BinaryTreeNode {
	private int info;
	private BinaryTreeNode left;
	private BinaryTreeNode right;

	public BinaryTreeNode() {
		super();
	}

	public BinaryTreeNode(int info) {
		super();
		this.info = info;
	}

	public BinaryTreeNode(int info, BinaryTreeNode left, BinaryTreeNode right) {
		super();
		this.info = info;
		this.left = left;
		this.right = right;
	}
}

BinaryTree類:

/**
 * 設計二叉樹類(BinaryTree),該類內部使用二叉樹結構存放二叉樹節點 (BinaryTreeNode),每個節點可存放一個整數值。
 * 該二叉樹類提供方法進行節點的追加(追加節點時,構建二叉排序樹),並提 供中序遍歷二叉樹節點的方法。
 *
 */
public class BinaryTree {
	private static BinaryTreeNode root;

	public static void main(String[] args) {
		BinaryTreeNode node = null;
		int[] array = {10,3,20,7,5,33,27,100,0};
		for(int i=0;i<array.length;i++){
			node = new BinaryTreeNode(array[i]);
			addTreeNode(node);
		}
		inOrderTraversal();//輸出結果:0,3,5,7,10,20,27,33,100,
	}

	/**
	 * 中序遍歷二叉樹
	 */
	private static void inOrderTraversal() {
		if (root == null) {
			return;
		}
		middleOrder(root);
	}
	
	private static void middleOrder(BinaryTreeNode current) {
		if (current.getLeft() != null) {
			// 遍歷左子樹
			middleOrder(current.getLeft());
		}
		System.out.print(current.getInfo() + ",");
		if (current.getRight() != null) {
			// 遍歷右子樹
			middleOrder(current.getRight());
		}
	}

	/**
	 * 追加二叉樹節點;追加節點時,構建二叉排序樹
	 * 
	 * @param node
	 * @return
	 */
	private static boolean addTreeNode(BinaryTreeNode node) {
		if (root == null) {
			root = node;
			return true;
		}
		BinaryTreeNode current = root;
		while (node != null) {
			if (node.getInfo() < current.getInfo()) {
				if (current.getLeft() == null) {
					current.setLeft(node);
					return true;
				} else {
					current = current.getLeft();
				}
			} else if (node.getInfo() > current.getInfo()) {
				if (current.getRight() == null) {
					current.setRight(node);
					return true;
				} else {
					current = current.getRight();
				}
			} else {
				//二叉排序樹中,不能存在數值相等的節點,否則錯誤
				System.out.println("repeat");
				return false;
			}
		}
		return false;
	}
}

 

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