排序二叉樹-添加以及遍歷

排序二叉樹

對於任何一個非葉子節點,要求左子樹的值比當前節點的值小,右子樹的值比當前節點的值大。如果有相同的值,則可以放置左右任意節點

添加及遍歷
package xmht.datastructuresandalgorithms.datastructure.binarysortTree;

/**
 * @author shengjk1
 * @date 2020/6/15
 */
public class BinarySortTree {
	public static void main(String[] args) {
		int[] arr = {7, 3, 10, 12, 5, -1, 9};
		BinarySortTree1 binarySortTree = new BinarySortTree1();
		for (int i : arr) {
			binarySortTree.add(new Node(i));
		}
		System.out.println("中序遍歷二叉樹");
		binarySortTree.infixOrder();
	}
}

class BinarySortTree1 {
	private Node root;
	
	public void add(Node node) {
		if (this.root != null) {
			this.root.add(node);
		} else {
			root = node;
		}
	}
	
	public void infixOrder() {
		if (this.root != null) {
			this.root.infixOrder();
		}
	}
	
	@Override
	public String toString() {
		return "BinarySortTree1{" +
				"root=" + root +
				'}';
	}
}

class Node {
	int value;
	Node left;
	Node right;
	
	public Node(int value) {
		this.value = value;
	}
	
	
	//添加節點
	//遞歸的形式添加,需要滿足二叉排序樹的要求
	public void add(Node node) {
		if (node == null) {
			return;
		}
		//判斷傳入節點的值,和當前子樹的根節點的值的關係
		if (node.value < this.value) {
			if (this.left == null) {
				this.left = node;
			} else {
				//遞歸的向左子樹添加
				this.left.add(node);
			}
		} else {
			if (this.right == null) {
				this.right = node;
			} else {
				this.right.add(node);
			}
		}
	}
	
	//中序遍歷
	public void infixOrder() {
		if (this.left != null) {
			this.left.infixOrder();
		}
		System.out.println(this);
		
		if (this.right != null) {
			this.right.infixOrder();
		}
	}
	
	
	@Override
	public String toString() {
		return "Node{" +
				"value=" + value +
				'}';
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章