1. 程式人生 > >Java構造一顆簡單的二叉樹

Java構造一顆簡單的二叉樹

package Arrays;

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

public class BinaryTree <T>{
	//靜態內部類不能訪問外部類的非靜態成員
	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 List<Node>preOrder(){
		return preOrderTraverse(root);
	}
	public List<Node>preOrderTraverse(Node node){
		List<Node>list=new ArrayList<Node>();
		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<Node> inOrder() {
		return inOrderTraverse(root);
	}
	public List<Node> inOrderTraverse(Node node) {
		List<Node>list=new ArrayList<Node>();
		if(node.lNode!=null)
			list.addAll(inOrderTraverse(node.lNode));
		list.add(node);
		if(node.rNode!=null)
			list.addAll(inOrderTraverse(node.rNode));
		return list;
	}
	//後序遍歷
	public List<Node>postOrder(){
		return postOrderTraverse(root);
	}
	
	public List<Node>postOrderTraverse(Node node){
		List<Node>list=new ArrayList<Node>();
		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) {
		BinaryTree<String>tree=new BinaryTree<String>("根節點");
		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);
		
		List<Node>node1=new ArrayList<Node>();
		node1=tree.preOrder();
		System.out.println("前序遍歷的結果是:");
		for (Node node : node1) {
			System.out.println(node.data);
		}
		
		List<Node>nodes=new ArrayList<Node>();
		nodes=tree.inOrder();
		System.out.println("中序遍歷的結果是:");
		for(Node i:nodes) {
			System.out.println(i.data);
		}
		
		List<Node>node2=new ArrayList<Node>();
		node2=tree.postOrder();
		System.out.println("後序遍歷的結果是:");
		for(Node i:node2) {
			System.out.println(i.data);
		}
	}
}