//二叉搜索树:没有重复元素,对于树中的每一个节点,它的左子树值都小于该节点的值,而它的右子树中节点的值都大于该节点的值,是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();
}
}