用int数组,通过层序遍历的方法,创建一个简单的二叉树,并进行先序遍历、中序遍历、后续遍历,以下见代码:
public class BaseOperation {
public static void main(String[] args) {
int[] arrs = {1,2,3,4,5,6,7,8,9};
TreeNode root = createTree(arrs);
preorder(root);
System.out.println();
inorder(root);
System.out.println();
afterorder(root);
}
/**
* 层序遍历的方法,创建一棵树
*/
public static TreeNode createTree(int[] arrs){
ArrayList<TreeNode> datas=new ArrayList<TreeNode>();
for(int value : arrs){
datas.add(new TreeNode(value));
}
TreeNode root=datas.get(0);
for (int i = 0; i <arrs.length/2; i++) {
//左孩子
datas.get(i).left=datas.get(i*2+1);
//右孩子
if(i*2+2<datas.size()){
datas.get(i).right=datas.get(i*2+2);
}
}
return root;
}
/**
* 先序遍历
*/
public static void preorder(TreeNode root){
if(root!=null){
System.out.print(root.value + " ");
preorder(root.left);
preorder(root.right);
}
}
/**
* 中序遍历
*/
public static void inorder(TreeNode root){
if(root!=null){
inorder(root.left);
System.out.print(root.value + " ");
inorder(root.right);
}
}
/**
* 后序遍历
*/
public static void afterorder(TreeNode root){
if(root!=null){
afterorder(root.left);
afterorder(root.right);
System.out.print(root.value + " ");
}
}
}
/**
* 节点的存储结构
*/
class TreeNode{
int value;
TreeNode left;
TreeNode right;
TreeNode(int x){
this.value = x;
this.left = null;
this.right = null;
}
}