思路:
首先需要考虑使用什么样的数据结构来进行转换,比如说是要栈还是队列,从线性结构转换为非线性结构。
1.将数组转为list对象。该list应该为双端队列的线性结构。
2.判断先出来的对象是否为空,空则不处理,否则创建二叉树对象。(二叉树很多时候可以采用递归的方法实现)
具体代码实现:
public static void main(String[] args) {
//创建linkedlist对象,类似于双向队列(先进先出)
LinkedList<Integer> list = new LinkedList<Integer>(Arrays.asList(new Integer[]{1,2,null,3,5,null}));
TreeNode root = createBinaryTree(list);
System.out.println(inorderTraversal(root));
}
public static TreeNode createBinaryTree(LinkedList<Integer> inputList){
TreeNode node=null;
if(inputList == null || inputList.isEmpty()){
return null;
}
//取出队列中的第一个元素
Integer data=inputList.removeFirst();
if(data != null){
//如果不为空,则创建新的对象 构造方法需要添加一个只用data的构造函数
node = new TreeNode(data);
//左节点使用同样递归的方法实现
node.left=createBinaryTree(inputList);
node.right=createBinaryTree(inputList);
}
return node;
}
//创建一个二叉树类
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}