和105一样的。。这个是给IN 和 POST
POST的最后一个是ROOT
所以就从后找,几乎一样的
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder.length == 0) return null;
int length = postorder.length;
int tailVal = postorder[length-1];
int tempIndex = length-1;
while(tailVal != inorder[tempIndex])
{
tempIndex--;
}
TreeNode root = new TreeNode(tailVal);
int[] newIn = Arrays.copyOfRange(inorder,tempIndex+1,length);
int[] newPost = Arrays.copyOfRange(postorder,tempIndex,length-1);
root.right = buildTree(newIn,newPost);
newIn = Arrays.copyOfRange(inorder,0,tempIndex);
newPost = Arrays.copyOfRange(postorder,0,tempIndex);
root.left = buildTree(newIn,newPost);
return root;
}
二刷。
二刷做的我想打人了。
尝试不建新Array,迭代4个index,结果没找对关系,浪费了好多时间。
最后老老实实重新copyRangeOf了。
感觉直接用INDEX是可以实现的。
public class Solution
{
public TreeNode buildTree(int[] in, int[] po)
{
if(in.length == 0) return null;
return generate(in,po);
}
public TreeNode generate(int[] in, int[] po)
{
if(in.length == 0) return null;
if(in.length == 1) return new TreeNode(po[0]);
int rootVal = po[po.length-1];
int temp = 0;
TreeNode root = new TreeNode(rootVal);
for(int i = 0; i < in.length ;i++)
{
if(in[i] == rootVal)
{
temp = i;
break;
}
}
int[] leftIn = Arrays.copyOfRange(in,0,temp);
int[] leftPo = Arrays.copyOfRange(po,0,temp);
root.left = generate(leftIn,leftPo);
int[] rightIn = Arrays.copyOfRange(in,temp+1,in.length);
int[] rightPo = Arrays.copyOfRange(po,temp,po.length-1);
root.right = generate(rightIn,rightPo);
return root;
}
}
Got my ass kicked by 90%+ ppl.
三刷。
postOrder的最后一个一定是当前ROOT。
在InOrder里寻找ROOT.VAL,找到位置的左边是LEFT,右边是RIGHT,进行递归。
一刷二刷是新建了ARRAY,没必要,直接记录进入递归的区间就可以了。
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return convert(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
}
public TreeNode convert(int[] in, int inL, int inR,
int[] post, int postL, int postR) {
if (postL > postR) return null;
if (postL == postR) return new TreeNode(post[postR]);
TreeNode res = new TreeNode(post[postR]);
int i = 0;
while (post[postR] != in[inR - i]) i++;
res.left = convert(in, inL, inR-i-1, post, postL, postR-i-1);
res.right = convert(in, inR-i+1, inR, post, postR-i, postR-1);
return res;
}
}