1.输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路:从最简单的树来想,建造一棵二叉树就是先找到根,然后建立左子树然后建立右子树,当给出的是遍历的数组时,可以根据遍历特点知道根节点,在先序遍历中,根节点总是第一个,然后在中序遍历中找到这个根节点,左边的是左子树,右边是右子树。对于复杂的二叉树这就是一个递归过程。
由于先序遍历的数组我需要一直往后遍历,我用队列的方式每次弹出第一个已经找到的根节点,中序遍历的数组我需要保存每次划分的数组的子数组,但是java对数组时传址的,所以就用Arrays.copyOfRange(in,0,temp)这个函数。(还学习到:java中队列的实现类是linklist,将数组初始化到队列中有2个方法:①Queue<Integer>queue=new
LinkedList<>(Arrays.asList(ppre));//这样的构造函数需要传入一个collection<?extends E> c,即c是y一个集合类,元
素继承E(这里是Integer)
②Queue<Integer>queue=new LinkedList<>(); //分两步构造,如果不是实现类不是链表而是数组,则需要传入一个长度
Collections.addAll(queue,
ppre)
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
Queue<Integer>queue=new LinkedList<>();
Integer[] ppre=new Integer[pre.length];
for(int i=0;i<ppre.length;i++){
ppre[i]=pre[i];
}
Collections.addAll(queue, ppre);
return reConstructBinary(queue,in);
}
public TreeNode reConstructBinary(Queue<Integer>pre,int []in) {
int val=0;
if(pre.size()>0){
val =pre.poll();
}
if(in.length<1||in==null) return null;
TreeNode root=new TreeNode(val);
root.left=null;
root.right=null;
int temp=0;
for(int i=0;i<in.length;i++){
if(val==in[i]){
temp=i;
break;
}
}
//左子树
if(temp>0){
root.left=reConstructBinary(pre,Arrays.copyOfRange(in,0,temp));
}
//右子树
if(temp<in.length-1){
root.right=reConstructBinary(pre,Arrays.copyOfRange(in,temp+1,in.length));
}
return root;
}
}
2.输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果,假设输入的数组的任意两个数字都互不相同。找到根,在数组中找到第一个比根大的节点,这个节点后面的节点都要比根节点大(相当于右子树)。
import java.util.*;
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence==null||sequence.length==0)
return false;
int root=sequence[sequence.length-1];
int i=0;
for(;i<sequence.length-1;i++){
if(sequence[i]>root){
break;
}
}
int j=i;
for(;j<sequence.length-1;j++){
if(sequence[j]<root)
return false;
}
boolean left=true;
boolean right=true;
if(i>0){
<span style="white-space:pre"> </span>//判断左子树
left=VerifySquenceOfBST(Arrays.copyOfRange(sequence, 0, i));
}
if(i<sequence.length-1){
<span style="white-space:pre"> </span>//判断右子树
right=VerifySquenceOfBST(Arrays.copyOfRange(sequence, i, sequence.length-1));
<span style="white-space:pre"> </span>}
return (left&&right);
}
}