java操作二叉树

时间:2021-11-20 17:27:30
/*
题目:用java语言创建二叉树,完成二叉树的建立和遍历;

*/
import java.util.Scanner;
class  BinaryTreeDemo
{
	public static void main(String[] args) 
	{
		Node binaryNode = new Node();
		BinaryTree binaryTree = new BinaryTree(binaryNode);
		System.out.println("创建二叉树:");
		binaryNode = binaryTree.createBinaryTree();
		System.out.println("前序遍历:");
		binaryTree.PreTree(binaryNode);
		System.out.println();
		System.out.println("中序遍历");
		binaryTree.InOrderTree(binaryNode);
		System.out.println();
		System.out.println("后序遍历");
		binaryTree.PostOrderTree(binaryNode);

	}
}

/*
二叉树特点:
最多有两个节点
*/
class Node
{
	// 存储二叉树节点值
	public int data;
	// 左节点
	public Node leftChild;
	// 右节点
	public Node rightChild;
}

class BinaryTree
{
	//创建一个父节点
	private Node rootNode;
	public BinaryTree(Node rootNode)
	{
		this.rootNode = rootNode;
	}

	//  按前序建立二叉树
	public Node createBinaryTree()
	{
		Node temp = new Node();
		Scanner sc = new Scanner(System.in);
		int value = sc.nextInt();
		if(value == 0)		//输入0表示该节点为空
		{
			temp = null;
		}
		else
		{
			temp.data = value;
			temp.leftChild = createBinaryTree();
			temp.rightChild = createBinaryTree();
		}

		return temp;
	}
	//  前序遍历
	public void PreTree(Node t)
	{
		if(t == null)
			return;
		System.out.print(t.data + " ");
		PreTree(t.leftChild);
		PreTree(t.rightChild);
	}

	//  中序遍历
	public void InOrderTree(Node t)
	{
		if(t == null)
			return;
		InOrderTree(t.leftChild);
		System.out.print(t.data + " ");
		InOrderTree(t.rightChild);
	}

	//  后序遍历
	public void PostOrderTree(Node t)
	{
		if(t == null)
			return;
		PostOrderTree(t.leftChild);
		PostOrderTree(t.rightChild);
		System.out.print(t.data + " ");
	}
}