只是为了好玩我试图在树上创建有序和后序,我知道网上有很多解决方案,但我自己做,觉得我非常接近,这是我的代码:
使用当前输入,我希望树
7
5 10
4 6 8 11
然而我得到的是
7
5 10
4 6 11 11
public static TreeNode buildTreeHelper(int[] inorder, int[] postorder, int inOrderIndex, int end){
if(end<0 || inOrderIndex<0){
return null;
}
TreeNode root = new TreeNode(postorder[end]);
int index = search(inorder,inOrderIndex,end,root.val);
if(index!=-1){
root.left = buildTreeHelper(inorder, postorder,inOrderIndex,index-1);
root.right= buildTreeHelper(inorder, postorder,index+1,end-1);
}
return root;
}
public static int search(int[]inorder, int start, int end, int target){
for(int i=start; i<=end; i++){
if(inorder[i]==target){
return i;
}
}
return -1;
}
public static void main(String[] args){
int[] inorder = {4, 5, 6, 7, 8, 10, 11};
int[] postorder = {4, 6, 5, 8, 11, 10, 7};
TreeNode ret = buildTreeHelper(inorder, postorder, 0, inorder.length-1);
}
答案 0 :(得分:0)
我认为您的inOrderIndex
和end
参数可以变为inOrderIndex > end
。所以我会检查这个逻辑。我会进行调试,以确定您在哪一点上缺少值8
并使用10
代替。
答案 1 :(得分:0)
以下是解决问题的建议步骤:
在构建正确树的解决方案中,有序数组的起始索引等于后序数组的起始索引,这是不正确的。例如,在第一次迭代中,根是7,有序索引是3,右树的有序数组的起始索引是4,其中存储值8,但是后序的起始索引是3,其中商店值为8.因此,您需要为有序和后期订单提供单独的索引。
解决方案看起来像
public static TreeNode buildTreeHelper(int[] inorder, int[] postorder,
int inOrderStart, int inOrderEnd, int postOrderStart, int postOrderEnd) {
if (inOrderEnd < 0 || inOrderStart < 0 || postOrderEnd < 0
|| postOrderStart < 0) {
return null;
}
TreeNode root = new TreeNode(postorder[postOrderEnd]);
// special case: when the node is a leaf
if (inOrderStart == inOrderEnd) {
return root;
}
int index = search(inorder, inOrderStart, inOrderEnd, root.val);
if (index != -1) {
//get the length of the left tree
int leftTreeLen = index - inOrderStart;
root.left = buildTreeHelper(inorder, postorder, inOrderStart,
index - 1, postOrderStart, postOrderStart + leftTreeLen - 1);
root.right = buildTreeHelper(inorder, postorder, index + 1,
inOrderEnd, postOrderStart + leftTreeLen, postOrderEnd - 1);
}
return root;
}
public static int search(int[] inorder, int start, int end, int target) {
for (int i = start; i <= end; i++) {
if (inorder[i] == target) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int[] inorder = { 4, 5, 6, 7, 8, 10, 11 };
int[] postorder = { 4, 6, 5, 8, 11, 10, 7 };
TreeNode ret = buildTreeHelper(inorder, postorder, 0,
inorder.length - 1, 0, postorder.length - 1);
}