二叉树

二叉树

二叉树结点的构建

<pre>
class BinNode{
	public int data;
	public int height;
	public BinNode parent;
	public BinNode left;
	public BinNode right;
	public BinNode(int data) {
		super();
		this.data = data;
		this.height = 0; 
		this.parent = null;
		this.left = null;
		this.right = null;
	}
	public BinNode insertLeftNode(int data) {
		//在当前结点左边插入节点
		if(this.left == null) {
			BinNode leftNode = new BinNode(data);
			this.left = leftNode;
			leftNode.parent = this;
		}else {
			System.out.println("当前节点的左节点不为空");
		}
		return this.left;
	}
	public BinNode insertRightNode(int data) {
		//在当前结点右边插入结点
		if (this.right == null) {
			BinNode rightNode = new BinNode(data);
			this.left = rightNode;
			rightNode.parent = this;
		}else {
			System.out.println("当前节点的右节点不为空");
		}
		return this.right;
	}
	public int size() {
		//返回当前节点的子节点的个数(包括当前节点)
		int s = 1;
		if (this.left != null) {
			s += this.left.size();
		}
		if (this.right != null) {
			s += this.right.size();
		}
		return s;
	}
}
</pre>

二叉树的构建及其相关接口

<pre>
class BinTree{
	public BinNode root;
	public int treeSize;
	
	public BinTree() {
		this.root = null;
	}
	public BinTree(BinNode node) {
		//设置根节点
		this.root = node;
	}
	
	public boolean isEmpty() {
		//判读树是否为空
		return this.root == null ? true : false;
	}
	public int updateHeight(BinNode node) {
		//更新当前节点的height
		int subHeight = node.left.height > node.right.height? node.left.height : node.right.height;
		node.height = 1 + subHeight;
		return node.height;
	}
	public void updateHeightOver(BinNode node) {
		//更新当前节点及其父节点的height
		while(node.parent != null) {
			node.height = updateHeight(node);
			node = node.parent;
		}
	}
	public BinNode insertLeftNode(BinNode x, int data) {
		//在x节点的左侧插入节点,节点中的数据为data
		BinNode xLeft = x.insertLeftNode(data);
		updateHeightOver(x);
		return xLeft;
	}
	public BinNode insertRightNode(BinNode x, int data) {
		//在x节点的右侧插入节点,节点中的数据为data
		BinNode xRight = x.insertRightNode(data);
		updateHeightOver(x);
		return xRight;
		
	}
	public BinNode insertRightTree(BinNode x, BinTree tree) {
		//在x结点的右侧插入子树tree;
		if (x.right == null) {
			x.right = tree.root;
		}else {
			System.out.println("无法插入");
		}
		updateHeightOver(x);
		return x.right;
	}
	public BinNode insertLeftTree(BinNode x, BinTree tree) {
		//在x结点的左侧插入子树tree;
		if (x.left == null) {
			x.left = tree.root;
		}else {
			System.out.println("无法插入");
		}
		updateHeightOver(x);
		return x.left;
	}
	public void removeLeftTree(BinNode x) {
		//删除x的左子树
		x.left = null;
		updateHeightOver(x);
	}
	public void removeRightTree(BinNode x) {
		//删除x的右子树
		x.right = null;
		updateHeightOver(x);
	}
}
</pre>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值