一般来说我们得到的先序遍历和逐层遍历的序列都不能转回二叉树,但是如果我们把叶子节点的null孩子也储存起来就可以,也就是把null看成叶子结点。
这里用一个Integar链表来表示数据。
先序遍历思路:
递归为每个非null节点分配孩子节点。核心思想还是先序遍历。
代码:
//先序遍历队列还原二叉树
public BinaryTreeNode generateTree(LinkedList<Integer> queue){
int value=queue.poll();
BinaryTreeNode root=new BinaryTreeNode(value, null, null);
dispatchNode(root, queue);
return root;
}
//为每一个节点分配孩子
public void dispatchNode(BinaryTreeNode node,LinkedList<Integer> queue){
Integer leftValue=queue.poll();
if(leftValue!=null){
BinaryTreeNode left=new BinaryTreeNode(leftValue, null, null);
node.setLeftChild(left);
dispatchNode(left,queue);
}
Integer rightValue=queue.poll();
if(rightValue!=null){
BinaryTreeNode right=new BinaryTreeNode(rightValue, null, null);
node.setRightChild(right);
dispatchNode(right,queue);
}
}
测试数据:
//先序遍历测试
public static void main(String[] args){
LinkedList<Integer> queue=new LinkedList<>();
queue.offer(1);
queue.offer(2);
queue.offer(4);
queue.offer(null);
queue.offer(null);
queue.offer(null);
queue.offer(3);
queue.offer(5);
queue.offer(7);
queue.offer(null);
queue.offer(null);
queue.offer(8);
queue.offer(null);
queue.offer(null);
queue.offer(6);
queue.offer(null);
queue.offer(null);
test test=new test();
test.generateTree(queue).print();
}
维护一个等待分配孩子的链表A,每次遍历取出一层的节点并将它们的孩子放入A,这样新的A就是下一层的所有节点。重复该操作即可。
代码:
public BinaryTreeNode geneTree(LinkedList<Integer> queue){
LinkedList<BinaryTreeNode> queueWait=new LinkedList<>();//等待分配的队列
Integer value=queue.poll();
BinaryTreeNode root=new BinaryTreeNode(value, null, null);
queueWait.offer(root);
while(!queueWait.isEmpty()){
int length=queueWait.size();
for(int i=0;i<length;i++){
BinaryTreeNode node=queueWait.poll();
Integer leftValue=queue.poll();
if(leftValue!=null){
BinaryTreeNode left=new BinaryTreeNode(leftValue, null, null);
node.setLeftChild(left);
queueWait.offer(left);
}
Integer rightValue=queue.poll();
if(rightValue!=null){
BinaryTreeNode right=new BinaryTreeNode(rightValue, null, null);
node.setRightChild(right);
queueWait.offer(right);
}
}
}
return root;
}
测试数据:
//逐层遍历测试
public static void main(String[] args){
LinkedList<Integer> queue=new LinkedList<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
queue.offer(null);
queue.offer(5);
queue.offer(6);
queue.offer(null);
queue.offer(null);
queue.offer(7);
queue.offer(8);
queue.offer(null);
queue.offer(null);
queue.offer(null);
queue.offer(null);
queue.offer(null);
queue.offer(null);
test test=new test();
test.geneTree(queue).print();
}