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;
	}
}

 

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