1.今天突发奇想,想将一个一维数组转换为二叉树存储,花了一下午的时间思考,得出的代码,代码还不是最终版本,我感觉可以简化,但是可以实现基本功能,能基本实现将一个一维数组转换为二叉树存储。
2.代码如下:其中有详细解释,后续我会补充先序,中序,后序,层次遍历。
package com.data_struct.tree;
public class Binary_tree
{
public static void main(String[] args)
{
//一开始我们采用最原始的做法,一个节点一个节点的连接。我们发现了如下规律,
//每一个子节点的位置坐标除以2取整以后是父节点的位置
int[] a = {1, 2, 3, 4, 5};
//a1节点
node a1 = new node(null, 1, null);
//a1是父节点,a2和a3是a1的子节点,我们利用上述的二叉树定律,2%2=1,3%2=1
//我们发现通过子节点坐标是可以找到父节点的。
node a2 = new node(null, 2, null);
a1.left = a2;
node a3 = new node(null, 3, null);
a1.right = a3;
//a2节点
node a4 = new node(null, 4, null);
a2.left = a4;
node a5 = new node(null, 5, null);
a2.right = a5;
}
}
class node
{
public node left = null;
public int value;
public node right = null;
public node(node left, int value, node right)
{
this.left = left;
this.value = value;
this.right = right;
}
}
class binaryTree
{
private node root = new node(null, 0, null);
private node rear ;
private int number = 0;
private int[] data;
public binaryTree(int[] data)//得到目标数组
{
this.data = data;
}
//这个方法用的就是上述子节点和父节点位置坐标的关系,将每一个产生的节点指针存进数组,
// 然后通过子节点位置%2得到父节点位置,
public void initTree()
{
root.value = data[0];
node[] nodeArray=new node[data.length];
nodeArray[0]=root;
for (int i = 1; i < data.length; i++)
{
node a = new node(null, data[i], null);
//创建新节点。
nodeArray[i]=a;
//存储新节点位置
rear=nodeArray[(i+1)/2-1];
//通过除数求整找到父节点位置,然后挂链。
if (i % 2 != 0)
{
rear.left = a;
} else
rear.right = a;
//通过判断是放在左子树还是右子树。
}
}
}



