package main;
class Node{
public int data;
public Node left;
public Node right;
public Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}
public class BinaryNode {
public Node root;
public BinaryNode(){
root=null;
}
//插入节点
public void insert(int data)
{
Node newNode=new Node(data);
if(root==null)
{
root=newNode;
}
else{
Node current=root;
Node parent;
while(true)
{
parent=current;
if(data<current.data)
{
current=current.left;
if(current==null)
{
parent.left=newNode;
return;
}
}
else
{
current=current.right;
if(current==null)
{
parent.right=newNode;
return;
}
}
}
}
}
//创建二叉树
public void buidTree(int[] data)
{
for(int i=0;i<data.length;i++)
{
insert(data[i]);
}
}
//递归法中序遍历
public void order(Node node)
{
if(node!=null)
{
order(node.left);
System.out.print(node.data+" ");
order(node.right);
}
}
// 递归法前序遍历
public void before(Node node)
{
if(node!=null)
{
System.out.print(node.data+" ");
before(node.left);
before(node.right);
}
}
// 递归后序遍历
public void later(Node node)
{
if(node!=null)
{
later(node.left);
later(node.right);
System.out.print(node.data+" ");
}
}
public static void main(String[] args){
BinaryNode bitTree=new BinaryNode();
int[] data={2,8,7,4,9,3,1,6,7,5};
bitTree.buidTree(data);
//前序遍历结果
System.out.println("前序遍历结果");
bitTree.before(bitTree.root);
System.out.println();
// 中序遍历结果
System.out.println("中序遍历结果");
bitTree.order(bitTree.root);
System.out.println();
// 后序遍历结果
System.out.println("后序遍历结果");
bitTree.later(bitTree.root);
System.out.println();
}
}
输出结果:
前序遍历结果
2 1 8 7 4 3 6 5 7 9
中序遍历结果
1 2 3 4 5 6 7 7 8 9
后序遍历结果
1 3 5 6 4 7 7 9 8 2