二叉樹

二叉樹

二叉樹結點的構建

<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>
發佈了11 篇原創文章 · 獲贊 0 · 訪問量 1765
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章