虽然这个问题不发展,但网上关于这个题的代码太少了,这里贴一个。
public class Solution {
public static void main(String[] args) {
Offer_07_2 o = new Offer_07_2();
int[] preorder = new int[]{3,9,20,15,7};
int[] inorder = new int[]{9,3,15,20,7};
int[] res = o.printPostorder(preorder,inorder);
for(int i=0;i
System.out.print(res[i]+" ");
}
public List res = new ArrayList<>();
public int[] printPostorder(int[] preorder, int[] inorder) {
if(preorder == null || preorder.length ==0)
return new int[]{};
recur(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
int ans[] = new int[res.size()];
for(int i=0;i
ans[i] = res.get(i);
}
return ans;
}
public void recur(int[] preorder,int[] inorder,int pre_left,int pre_right,int in_left,int in_right){
if(in_left > in_right)
return;
int rootVal = preorder[pre_left];
int in_mid;
for(in_mid=in_left;in_mid<=in_right;in_mid++){
if(inorder[in_mid] == rootVal)
break;
}
recur(preorder,inorder,pre_left+1,pre_left+in_mid-in_left,in_left,in_mid-1);
recur(preorder,inorder,pre_left+in_mid-in_left+1,pre_right,in_mid+1,in_right);
res.add(rootVal);
}
}
当然,当我们将res.add(rootVal)写到recur的不同位置时,就会输出对应的前中后序序列。
此外,使用前序和中序构造二叉树也是同理,如下所示:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || preorder.length ==0)
return null;
return build(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
}
public TreeNode build(int[] preorder,int[] inorder,int pre_left,int pre_right,int in_left,int in_right){
if(in_left > in_right)
return null;
int rootVal = preorder[pre_left];
int in_mid;
for(in_mid=in_left;in_mid<=in_right;in_mid++){
if(inorder[in_mid] == rootVal)
break;
}
TreeNode root = new TreeNode(rootVal);
root.left = build(preorder,inorder,pre_left+1,pre_left+in_mid-in_left,in_left,in_mid-1);
root.right = build(preorder,inorder,pre_left+in_mid-in_left+1,pre_right,in_mid+1,in_right);
return root;
}
}