Java构造一颗简单的二叉树

package Arrays;

import java.util.ArrayList;
import java.util.List;

public class BinaryTree {
	//静态内部类不能访问外部类的非静态成员
	public static class Node{
		private Node lNode;
		private Node rNode;
		private Object data;
		
		public Node(Object data) {
			this.data=data;
		}
		//构造一个新结点,该结点以lNode结点为其左孩子,rNode结点为其右孩子
		public Node(Node lNode,Node rNode,Object data) {
			this.lNode=lNode;
			this.rNode=rNode;
			this.data=data;
		}
	}
	
	private Node root;//用一个根结点来表示二叉树
	
	public BinaryTree(Object data) {
		this.root=new Node(data);
	}
	//添加结点
	public Node addNode(Node parentNode,Object data,boolean isLeft) {
		//父节点为空,无法添加子节点
		if(parentNode==null)
			throw new RuntimeException("父节点为空,无法添加子节点");
		if (isLeft&&parentNode.lNode!=null)
			throw new RuntimeException("左子节点已经存在,添加失败");
		if(!isLeft&&parentNode.rNode!=null)
			throw new RuntimeException("右子节点已经存在,添加失败");
		Node newNode=new Node(data);
		if(isLeft) {
			parentNode.lNode=newNode;
		}else {
			parentNode.rNode=newNode;
		}
		return newNode;
	}
	
	//前序遍历
	public ListpreOrder(){
		return preOrderTraverse(root);
	}
	public ListpreOrderTraverse(Node node){
		Listlist=new ArrayList();
		list.add(node);
		if(node.lNode!=null)
			list.addAll(preOrderTraverse(node.lNode));
		if(node.rNode!=null)
			list.addAll(preOrderTraverse(node.rNode));
		return list;
	}
	//中序遍历
	public List inOrder() {
		return inOrderTraverse(root);
	}
	public List inOrderTraverse(Node node) {
		Listlist=new ArrayList();
		if(node.lNode!=null)
			list.addAll(inOrderTraverse(node.lNode));
		list.add(node);
		if(node.rNode!=null)
			list.addAll(inOrderTraverse(node.rNode));
		return list;
	}
	//后序遍历
	public ListpostOrder(){
		return postOrderTraverse(root);
	}
	
	public ListpostOrderTraverse(Node node){
		Listlist=new ArrayList();
		if(node.lNode!=null)
			list.addAll(postOrderTraverse(node.lNode));
		if(node.rNode!=null)
			list.addAll(postOrderTraverse(node.rNode));
		list.add(node);
		return list;
	}
	public static void main(String[] args) {
		BinaryTreetree=new BinaryTree("根节点");
		Node t11=tree.addNode(tree.root, "左结点", true);
		Node t12=tree.addNode(tree.root, "右结点", false);
		Node t21=tree.addNode(t11, "左结点的左结点", true);
		Node t22=tree.addNode(t11, "左结点的右结点", false);
		
		Listnode1=new ArrayList();
		node1=tree.preOrder();
		System.out.println("前序遍历的结果是:");
		for (Node node : node1) {
			System.out.println(node.data);
		}
		
		Listnodes=new ArrayList();
		nodes=tree.inOrder();
		System.out.println("中序遍历的结果是:");
		for(Node i:nodes) {
			System.out.println(i.data);
		}
		
		Listnode2=new ArrayList();
		node2=tree.postOrder();
		System.out.println("后序遍历的结果是:");
		for(Node i:node2) {
			System.out.println(i.data);
		}
	}
}

 

你可能感兴趣的:(Java构造一颗简单的二叉树)