Java模拟二叉树实现

阅读更多

      二叉树的概念不说了,搜索引擎比我说的更加清楚和完整。


      下面的例子允许将各种java.lang.Comparable的子类作为节点元素被添加到二叉树结构当中,并依据二叉树的中序遍历的方式将二叉树结构当中所有元素输出。


      二叉树结构的Java实现类

 

package org.tang.binarytree;

public class BinaryTree> {
	private Node root;
	
	public Node getRoot() {
		return root;
	}

	public void setRoot(Node root) {
		this.root = root;
	}
	
	public void addElement(T element){
		if(element == null){
			return;
		}
		Node node = new Node(element);
		if(this.root == null){
			this.root = node;
		}else{
			this.root.addChild(node);
		}
	}
	
	public void printBinaryTree(){
		if(this.root == null){
			System.out.println("当前为空对象,无法打印。");
			return;
		}
		this.root.printNode();
	}
	
	private static class Node>{
		private E nodeData;
		private Node left;
		private Node right;
		private Node(E nodeData){
			this.nodeData = nodeData;
		}
		
		private void addChild(Node child){
			if(child == null){
				return;
			}
			if(this.compareTo(child) >= 0){
				if(this.left == null){
					this.left = child;
				}else{
					this.left.addChild(child);
				}
			}else{
				if(this.right == null){
					this.right = child;
				}else{
					this.right.addChild(child);
				}
			}
		}
		
		private int compareTo(Node node){
			return this.nodeData.compareTo(node.nodeData);
		}
		
		private void printNode(){
			if(this.left != null){
				this.left.printNode();
			}
			System.out.println(this.nodeData.toString());
			if(this.right != null){
				this.right.printNode();
			}
		}
	}
}

 

      二叉树实现类的使用方式

 

package org.tang.binarytree;

public class Client {
	public static void main(String[] args){
		BinaryTree bt = new BinaryTree();
		bt.addElement(101);
		bt.addElement(45);
		bt.addElement(49);
		bt.addElement(1);
		bt.addElement(20);
		bt.addElement(-1);
		bt.printBinaryTree();
		
		BinaryTree bt2 = new BinaryTree();
		bt2.addElement("a");
		bt2.addElement("A");
		bt2.addElement("z");
		bt2.addElement("e");
		bt2.printBinaryTree();
	}
}
  • BinaryTreeSrc.jar (1.8 KB)
  • 下载次数: 6

你可能感兴趣的:(Binary,Tree,二叉树,Comparable,中序遍历)