/**
* 方法1
*/
public String getSumBinaryTreeInTraversal(int[] nums1,int[] nums2){
getBinaryTreeValue(nums1,0,nums1.length-1,nums2,0,nums2.length-1);
StringBuilder sb = new StringBuilder();
for (int num : nums2)
sb.append(num).append(" ");
if(sb.length() >= 2)
sb.delete(sb.length()-1,sb.length());
return sb.toString();
}
/**
* 递归方法:基于重构二叉树的改造
*/
public int getBinaryTreeValue(int[] pre,int preStart,int preEnd,int[] in,int inStart,int inEnd){
//递归终止条件
if(preStart > preEnd||inStart > inEnd || preEnd-preStart != inEnd-inStart)
return 0;
int rootIndex = inStart;
//在中序遍历结果中寻找当前子树的根节点索引
while(rootIndex <= inEnd && in[rootIndex] != pre[preStart])
rootIndex++;
//递归调用
int len = rootIndex - inStart;
int left = getBinaryTreeValue(pre,preStart+1,preStart+len,in,inStart,rootIndex-1);
int right = getBinaryTreeValue(pre,preStart+len+1,preEnd,in,rootIndex + 1,inEnd);
int oldValue = in[rootIndex];
in[rootIndex] = left + right;
return oldValue + in[rootIndex];
}