java——根據前序、中序遍歷結果重建二叉樹
阿新 • • 發佈:2018-12-26
如果已知一個二叉樹的前序、中序遍歷結果,要重建一個二叉樹,步驟如下:
二叉樹的四種遍歷方式
例:
二叉樹的前序遍歷結果:{1,2,4,7,3,5,6,8};
中序遍歷結果:{4,7,2,1,5,3,8,6};
我們知道樹的前序遍歷第一個數就是根節點,而在中序遍歷中,前面是左子樹,中間是根節點,後面是右子樹,於是對於這個二叉樹:
1、根節點:1
2、左子樹(就是在中序遍歷中找到根節點,前面的數就是左子樹的所有節點):中序遍歷中的{4,7,2},於是在前序中就是{2,4,7};
3、右子樹:中序遍歷中的{5,3,8,6},於是在前序中就是{3,5,6,8};
4、對左子樹、右子樹的前序中序結果遞迴進行前面的操作;
/** * 根據重建一個二叉樹主方法 * @param pre 前序遍歷的陣列 * @param inf 中序遍歷的陣列 * @return */ public static Tree.Entry rebuild(int [] pre,int [] inf) { if(pre == null || inf == null){ return null; } Tree<Integer>.Entry root = core(pre, inf, 0, pre.length-1, 0, inf.length-1); return root; } /** * 核心函式 * @param pre * @param inf * @param preStart * @param preEnd * @param infStart * @param infEnd * @return */ private static Tree.Entry core(int[] pre, int[] inf, int preStart, int preEnd, int infStart, int infEnd) { //根節點 Tree<Integer>.Entry root = new Tree().new Entry(pre[preStart]); root.left = null; root.right = null; //遞迴的終點,遞迴的終止條件 if (preStart == preEnd && infStart == infEnd) { return root; } //找到當前根在中序遍歷陣列的位置 int index = 0; for(index = infStart; index < infEnd; index++){ if (pre[preStart] == inf[index]) { break; } } int leifLength = index - infStart; //左子樹長度 int rightLength = infEnd - index; //右子樹長度 if (leifLength > 0) { //遞迴左子樹 root.left = core(pre, inf, preStart+1, preStart+leifLength, infStart, index-1); } if (rightLength > 0) { //遞迴右子樹 root.right = core(pre, inf, preStart+1+leifLength, preEnd, index+1, infEnd); } return root; //返回整個樹的根節點 }
測試程式碼:
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};
Tree<Integer> tree = new Tree<>();
tree.DLR(rebuild(pre,in));
System.out.println();
tree.LDR(rebuild(pre,in));
}
執行結果:
1 2 4 7 3 5 6 8 4 7 2 1 5 3 8 6