給定前序遍歷 pre[] = {1,2,4,5,3,6,7} 與中序遍歷 in[] = {4,2,5,1,6,3,7},重建二叉樹。
root = new TreeNode(pre[preStart])inRootIndexleftSize = inRootIndex - inStart[preStart+1, preStart+leftSize],中序 [inStart, inRootIndex-1][preStart+leftSize+1, preEnd],中序 [inRootIndex+1, inEnd]public class BinaryTreeReconstruction {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || inorder == null || preorder.length != inorder.length) {
return null;
}
return build(preorder, 0, preorder.length - 1,
inorder, 0, inorder.length - 1);
}
private TreeNode build(int[] pre, int preL, int preR,
int[] in, int inL, int inR) {
if (preL > preR || inL > inR) return null;
TreeNode root = new TreeNode(pre[preL]);
int inRootIdx = inL;
while (inRootIdx <= inR && in[inRootIdx] != pre[preL]) inRootIdx++;
int leftSize = inRootIdx - inL;
root.left = build(pre, preL + 1, preL + leftSize, in, inL, inRootIdx - 1);
root.right = build(pre, preL + leftSize + 1, preR, in, inRootIdx + 1, inR);
return root;
}
// 後序驗證
public void postOrder(TreeNode root) {
if (root == null) return;
postOrder(root.left);
postOrder(root.right);
System.out.print(root.val + " ");
}
public static void main(String[] args) {
int[] pre = {1,2,4,5,3,6,7};
int[] in = {4,2,5,1,6,3,7};
BinaryTreeReconstruction solver = new BinaryTreeReconstruction();
TreeNode root = solver.buildTree(pre, in);
solver.postOrder(root); // 輸出: 4 5 2 6 7 3 1
}
}
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}
同理可從「中序 + 後序」重建,前序換為後序最後一個元素為根。