1.由(preorder+inorder)复原
/* * preorder:先序遍历数组 * ps,pe:先序数组的首元素和末元素的索引 * inod:中序遍历数组 * is,ie:中序数组的首元素和末元素的索引 */ public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { return buildBT(preorder,0,preorder.length-1,inorder,0,inorder.length-1); } private TreeNode buildBT(int[] preorder,int ps,int pe,int[] inorder,int is,int ie) { if(pe<ps) return null; TreeNode root=new TreeNode(preorder[ps]); if(pe==ps) return root; int middle=0; for(int i=is;i<=ie;i++) if(inorder[i]==preorder[ps]) { middle=i; break; } int len=middle-is; root.left=buildBT(preorder,ps+1,ps+len,inorder,is,middle-1); root.right=buildBT(preorder,ps+len+1,pe,inorder,middle+1,ie); return root; } }
2.由(inorder+postorder)复原
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { return buildBT(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1); } private TreeNode buildBT(int[] inorder,int is,int ie,int[] postorder,int ps,int pe) { if(is>ie) return null; TreeNode root=new TreeNode(postorder[pe]); if(pe==ps) return root; int middle=0; for(int i=is;i<=ie;i++) if(inorder[i]==postorder[pe]) { middle=i; break; } int len=middle-is; root.left=buildBT(inorder,is,middle-1,postorder,ps,ps+len-1); root.right=buildBT(inorder,middle+1,ie,postorder,ps+len,pe-1); return root; } }