写的真费劲!!!!
我就是一道酸菜鱼,又酸,又菜,还多余
终于写出来了层序遍历二叉树,可以正常打印二叉树了;2019.3.1
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
return reConstructBT(0,pre.length-1,0,in.length-1,pre,in);
}
private TreeNode reConstructBT(int preStart,int preEnd,int inStart,int inEnd,int[] pre,int[] in){
TreeNode root = new TreeNode(pre[preStart]);
root.left = null;
root.right = null;
if(preStart == preEnd||inStart == inEnd){
return root;
}
int a = pre[preStart];
int index1 = getIndex(in,a);
int leftLength = index1 - inStart;
int rightLength = inEnd - index1;
if(leftLength>0){
root.left = reConstructBT(preStart+1,preStart+leftLength,inStart,index1-1,pre,in);
}
if(rightLength>0){
root.right = reConstructBT(preStart+leftLength+1,preEnd,index1+1,inEnd,pre,in);
}
return(root);
}
public static int getIndex(int[] arr, int value) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == value) {
return i;
}
}
return -1;
}
}
下面的代码是我自己在本地IDEA中测试重建二叉树的,层序遍历打印二叉树,非递归代码。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class BinaryTree {
public static void main(String[] args){
int[] in ={3,2,4,1,6,5,7};
int[] pre ={1,2,3,4,5,6,7};
BinaryTree BT = new BinaryTree();
TreeNode root = BT.reConstructBinaryTree(pre,in);
ArrayList<Integer> list = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root ==null){
System.out.println("二叉树为空");
}else{
queue.offer(root);
while(!queue.isEmpty()){
TreeNode root1 = queue.poll();
if (root1.left!=null){
queue.offer(root1.left);
}
if (root1.right!=null){
queue.offer(root1.right);
}
list.add(root1.val);
}
}
for(int i:list){
System.out.println(i);
}
}
//此处加上上文Solution内的代码
}