二叉搜索树的中序 前序 后序遍历JAVA实现

//二叉搜索树:没有重复元素,对于树中的每一个节点,它的左子树值都小于该节点的值,而它的右子树中节点的值都大于该节点的值,是Set集合实现的原生的数据结构

class Node{

int e;

Node left;

Node right;

public Node(int e){

this.e=e;

}

}

public class BinaryTree {

private Node root;

public BinaryTree(){//初始化一个空树,构造器的作用

root=null;

//后面整体两部分是用来构建二叉树的

//将数据e插入到排序二叉树中,利用二叉查找树的性质进行处理

public void insert(int e){

Node newN=new Node(e);//创建一个新的节点

//如果插入节点前二叉树是个空树

if(null==root){

root=newN;

}else{

//后面是比较正常的情况,就是插入节点算法的核心部分

Node cur=root;

Node par;//其实质就是寻找需要赋值节点的父亲节点

//寻找插入的位置

while(true){

par=cur;//从根节点开始找

if(e<cur.e){//向左边找

cur=cur.left;

if(cur==null){//找到空节点,赋值

par.left=newN;

return;

}

}else{//向右边找

cur=cur.right;

if(cur==null){//找到空节点,赋值

par.right=newN;

return;

}

}

}

}

}

//将数值输入构建一个二叉树

public void buildTree(int[] data){

for(int i=0;i<data.length;i++){

insert(data[i]);

}

}

//三大遍历比较常考的情况

//1.中序遍历方法递归实现

public void inorder(Node lroot){

if(lroot!=null){

inorder(lroot.left);

System.out.print(lroot.e+" ");

inorder(lroot.right);

}

}

//2.前序遍历方法递归实现

public void preorder(Node lroot){

if(lroot!=null){

System.out.print(lroot.e+" ");

preorder(lroot.left);

preorder(lroot.right);

}

}

//3.后序遍历方法递归实现

public void postorder(Node lroot){

if(lroot!=null){

postorder(lroot.left);

postorder(lroot.right);

System.out.print(lroot.e+" ");

}

}

 

 

 

//以上所有模块方法的测试情况如下

public static void main(String[] args) {

BinaryTree bt=new BinaryTree();

int[] data={2,8,7,4,9,3,1,6,7,5};

bt.buildTree(data);

System.out.print("二叉树的中序遍历:");

bt.inorder(bt.root);

System.out.println();

System.out.print("二叉树的前序遍历:");

bt.preorder(bt.root);

System.out.println();

System.out.print("二叉树的后序遍历:");

bt.postorder(bt.root);

System.out.println();

}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值