package com.plat.acoal.java8.model;
import java.util.Arrays;
import java.util.LinkedList;
public class TreeDemo {
/**
* 二叉树节点
*/
static class TreeNode{
//定义类变量
int data;
TreeNode leftchild;
TreeNode rightchild;
TreeNode(int data){
this.data=data;
}
}
/**
*
* 构建二叉树
* 输入序列
*/
public static TreeNode createBinaryTree(LinkedList<Integer> inputList){
TreeNode node=null;
if(inputList==null||inputList.isEmpty()){
return null;
}
Integer data=inputList.removeFirst();
if(data!=null){
node=new TreeNode(data);
node.leftchild=createBinaryTree(inputList);
node.rightchild=createBinaryTree(inputList);
}
return node;
}
/**
* 二叉树前序遍历
*/
private static void preOrderTraversal(TreeNode node){
if(node==null){
return;
}
System.out.println(node.data);
preOrderTraversal(node.leftchild);
preOrderTraversal(node.rightchild);
}
/**
* 二叉树中序遍历
*/
private static void inOrderTraversal(TreeNode node){
if(node==null){
return;
}
inOrderTraversal(node.leftchild);
System.out.println(node.data);
inOrderTraversal(node.rightchild);
}
/**
* 二叉树后序遍历
*/
private static void postOrderTraversal(TreeNode node){
if(node==null){
return;
}
postOrderTraversal(node.leftchild);
System.out.println(node.data);
postOrderTraversal(node.rightchild);
}
public static void main(String[] args) {
LinkedList<Integer> list=new LinkedList<Integer>(Arrays.asList(new Integer[]{3,4,8,null,null,10,null,null,8,null,4}));
TreeNode treeNode=createBinaryTree(list);
System.out.println("前序遍历:");
preOrderTraversal(treeNode);
System.out.println("中序遍历:");
inOrderTraversal(treeNode);
System.out.println("后序遍历:");
postOrderTraversal(treeNode);
}
}