1.重建二叉樹
【題目】
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列 {1,2,4,7,3,5,6,8} 和中序遍歷序列 {4,7,2,1,5,3,8,6},則重建二叉樹並返回。
【代碼】
package swear2offer.tree;
public class ReCreateTree {
/**
* 前序遍歷序列 {1,2,4,7,3,5,6,8}
* 中序遍歷序列 {4,7,2,1,5,3,8,6}
*
* 思路:
* 需要考慮遞歸的方式,本身樹這一結構就很適合進行遞歸
* 前序是 根、左、右
* 中序是 左、右、根
* 然後用遞歸的方式把左右節點放置在根節點之下
* */
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
return CreateTree(pre,0, pre.length,in,0,in.length);
}
public TreeNode CreateTree(int[] pre, int pStart,int pEnd,int[] in,int iStart,int iEnd) {
if (pStart>pEnd || iStart>iEnd ) return null;
if (pStart>=pre.length|| iStart>=in.length) return null;
int rootIndex,leftSize,rightSize;
TreeNode root = new TreeNode(pre[pStart]);
// 根節點在中序序列的下標
rootIndex = GetIndex(in,root.val);
// 左子樹長度
leftSize = rootIndex - iStart;
// 右子樹長度
rightSize = iEnd - rootIndex;
// 左子樹
root.left = CreateTree(pre,pStart+1,pStart+leftSize,
in,iStart,rootIndex-1);
// 右子樹
root.right = CreateTree(pre,pStart+leftSize+1,pEnd,
in,rootIndex+1,iEnd);
return root;
}
public int GetIndex(int[] a, int target) {
for(int i=0; i<a.length; i++) {
if (a[i] == target) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int[] pre = {1,2,4,7,3,5,6,8};
int[] in = {4,7,2,1,5,3,8,6};
TreeNode node = new ReCreateTree().reConstructBinaryTree(pre,in);
System.out.println(node);
}
}
【思路】
這類問題只需要用代碼實現解決問題的過程即可,但是需要注意的是**,遞歸的跳出和數組邊界越界**的問題,因爲隨着左邊界不斷右移,必然會出現越界的情況,需要在遞歸原有的跳出條件上加上越界判斷。