package demo;
import java.util.ArrayList;
import java.util.List;
public class TreeNode {
private TreeNode leftChild; //左子节点
private TreeNode rightChild; //右子节点
private int data; //根节点数据
public TreeNode(int data){
this.leftChild=null;
this.rightChild=null;
this.data=data;
}
/**将一个数组转换为二叉树结构
* @param datas
*/
public static List<TreeNode> createTreeNode(int[] datas){
List<TreeNode> list=new ArrayList<TreeNode>();
for(int i=0;i<datas.length;i++){ //依次创造节点
list.add(new TreeNode(datas[i]));
}
//依次建立二叉树
for(int i=0;i<datas.length/2-1;i++){
list.get(i).leftChild=list.get(2 * i + 1); //左子节点
list.get(i).rightChild=list.get(2 * i + 2); //右子节点
}
//最后一个父节点可能没有右子节点,所以单独处理
int lastParentIndex=datas.length/2-1;
list.get(lastParentIndex).leftChild=list.get(lastParentIndex * 2 + 1);
if(datas.length % 2 == 1){
list.get(lastParentIndex).rightChild=list.get(lastParentIndex * 2 + 2);
}
return list;
}
/**先序遍历
* @param node
*/
public static void preOrder(TreeNode node){
if(node==null){
return;
}
System.out.print(node.data+"----");
preOrder(node.leftChild);
preOrder(node.rightChild);
}
/**中序遍历
* @param node
*/
public static void inOrder(TreeNode node){
preOrder(node.leftChild);
System.out.print(node.data+"----");
preOrder(node.rightChild);
}
public static void postOrder(TreeNode node){
preOrder(node.leftChild);
preOrder(node.rightChild);
System.out.print(node.data+"----");
}
public static void main(String[] args) {
int[] datas = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<TreeNode> list=TreeNode.createTreeNode(datas);
System.out.println("先序遍历===>");
TreeNode.preOrder(list.get(0));
}
}