Java实现二叉搜索树

  这几天在看算法导论,昨晚上弄明白了二叉搜索树的一些操作和数据的组织结构。把伪代码转成Java来实现。

class Node {
	Node leftChild;
	Node rightChild;
	Node parent;
	int key;

	public Node(int key) {
		this.key = key;
	}
}

class BinarySearchTree {
	Node T = null;//树根

	public void TREE_INSERT(Node z) {
		Node y = null;
		Node x = T;
		while (x != null) {
			y = x;//y总指向x的父节点
			if (z.key < x.key)
				x = x.leftChild;
			else
				x = x.rightChild;
		}

		z.parent = y;
		if (y == null)//一开始是个空树
			T = z;
		else if (z.key < y.key)
			y.leftChild = z;
		else
			y.rightChild = z;
	}

	public Node TREE_SEARCH(Node x, int k) {
		if (x == null || k == x.key)
			return x;
		if (k < x.key)
			return TREE_SEARCH(x.leftChild, k);
		else
			return TREE_SEARCH(x.rightChild, k);
	}

	public Node TREE_MINIMUM(Node x) {
		while (x.leftChild != null)
			x = x.leftChild;
		return x;
	}

	public Node TREE_MAXIMUM(Node x) {
		while (x.rightChild != null)
			x = x.rightChild;
		return x;
	}

	public Node TREE_SUCCESSOR(Node x) {
		if (x.rightChild != null)
			return TREE_MINIMUM(x.rightChild);
		Node y = x.parent;
		while (y != null && x == y.rightChild) {
			x = y;
			y = y.parent;
		}
		return y;
	}

	public Node TREE_DELETE(Node z) {
		Node x, y;
		if (z.leftChild == null || z.rightChild == null)
			y = z;
		else//左右子树的都有
			y = TREE_SUCCESSOR(z);//求z的后继
		if (y.leftChild != null)
			x = y.leftChild;
		else
			x = y.rightChild;
		
		if (x != null)
			x.parent = y.parent;//z有两个子女的情况,x是y的左子树或右子树,y要么是z要么是z的后继

		if (y.parent == null)
			T = x;
		else if (y == y.parent.leftChild)
			y.parent.leftChild = x;
		else
			y.parent.rightChild = x;

		if (y != z)
			z.key = y.key;
		return y;
	}

	public void TREE_SEARCH_SHOW(Node x) {
		if (x == null)
			return;
		TREE_SEARCH_SHOW(x.leftChild);
		System.out.print(x.key + " ");
		TREE_SEARCH_SHOW(x.rightChild);
	}
}

public class Main {
	public static void main(String[] args) {
		BinarySearchTree tree = new BinarySearchTree();
		tree.TREE_INSERT(new Node(2));
		tree.TREE_INSERT(new Node(3));
		tree.TREE_INSERT(new Node(4));
		Node node6 = new Node(6);
		tree.TREE_INSERT(node6);
		tree.TREE_INSERT(new Node(7));
		tree.TREE_INSERT(new Node(9));
		Node node13 = new Node(13);
		tree.TREE_INSERT(node13);
		tree.TREE_INSERT(new Node(15));
		tree.TREE_INSERT(new Node(17));
		tree.TREE_INSERT(new Node(18));
		tree.TREE_INSERT(new Node(20));
		System.out.println(tree.TREE_SUCCESSOR(node6).key);
		System.out.println(tree.TREE_DELETE(node6).key);
		tree.TREE_SEARCH_SHOW(tree.T);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值