首先,定义一个树类Tree.java
public class Tree {
public TreeNode root;
}
定义树节点类TreeNode.java
public class TreeNode {
public TreeNode(int data) {
this.data = data;
}
public int data;
public TreeNode left;
public TreeNode right;
public void showData(){
System.out.println(data);//节点访问操作
}
}
二叉树的基本操作类 TreeUtils.java,
实现了增加树节点,删除树节点,搜索节点
生成二叉搜索树(左子树总小于右子树,中序遍历有序)
public class TreeUtils {
public static void addNode(Tree t,TreeNode node){
//将一个节点增加到已有二叉树(节点按二叉搜索树规则增加)
if(t.root==null){
t.root = node;
}else{
TreeNode current = t.root;//开始
while(true){
if(node.data<current.data){
if(current.left==null){
current.left = node;
return;
}else{
current = current.left;
continue;
}
}else{
if(current.right==null){
current.right = node;
return;
}else{
current = current.right;
continue;
}
}
}
}
}
public static void preOrderRecursive(TreeNode node){
//前序遍历
if(node