假設二叉樹的中序遍歷爲:
D B E A F C
先序遍歷爲:
A B D E C F
那麼,如何構建還原出這顆二叉樹?
算法思想:
先序遍歷中,第一個節點爲二叉樹根節點,本例中,根節點爲A,在中序遍歷集合中檢索字符A,字符A左邊的字符爲二叉樹左子樹,右邊的字符爲二叉樹右子樹。於是,我們得到如下結構:
遞歸重複上述步驟,得到如下結果:
算法實現buildTree:
- 從先序中檢索元素,元素位置索引preIndex,檢索preIndex+1位置的元素,用以下次遞歸中。
- 根據已檢索的元素構建一個新的節點tNode
- 在中序遍歷集合中檢索當前元素的位置索引index,記作inIndex
- 對於inIndex之前的元素集合,調用buildTree方法,結果作爲tNode的左子樹
- 對於inIndex之後的元素集合,調用buildTree方法,結果作爲tNode的右子樹
- 返回tNode節點
代碼實現:
public class InorderPreOrderToTree {
Node root;
static int preIndex = 0;
/* Recursive function to construct binary of size len from
Inorder traversal in[] and Preorder traversal pre[].
Initial values of inStrt and inEnd should be 0 and len -1.
The function doesn't do any error checking for cases where
inorder and preorder do not form a tree */
Node buildTree(char in[], char pre[], int inStrt, int inEnd) {
if (inStrt > inEnd)
return null;
/* Pick current node from Preorder traversal using preIndex
and increment preIndex */
Node tNode = new Node(pre[preIndex++]);
/* If this node has no children then return */
if (inStrt == inEnd)
return tNode;
/* Else find the index of this node in Inorder traversal */
int inIndex = search(in, inStrt, inEnd, tNode.data);
/* Using index in Inorder traversal, construct left and
right subtress */
tNode.left = buildTree(in, pre, inStrt, inIndex - 1);
tNode.right = buildTree(in, pre, inIndex + 1, inEnd);
return tNode;
}
/* UTILITY FUNCTIONS */
/* Function to find index of value in arr[start...end]
The function assumes that value is present in in[] */
int search(char arr[], int strt, int end, char value) {
int i;
for (i = strt; i <= end; i++) {
if (arr[i] == value)
return i;
}
return i;
}
/* This funtcion is here just to test buildTree() */
void printInorder(Node node) {
if (node == null)
return;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
System.out.print(node.data + " ");
/* now recur on right child */
printInorder(node.right);
}
// driver program to test above functions
public static void main(String args[]) {
InorderPreOrderToTree tree = new InorderPreOrderToTree();
char in[] = new char[]{'D', 'B', 'E', 'A', 'F', 'C'};
char pre[] = new char[]{'A', 'B', 'D', 'E', 'C', 'F'};
int len = in.length;
Node root = tree.buildTree(in, pre, 0, len - 1);
// building the tree by printing inorder traversal
System.out.println("Inorder traversal of constructed tree is : ");
tree.printInorder(root);
}
}
// Java program to construct a tree using inorder and preorder traversal
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class Node {
char data;
Node left, right;
Node(char item) {
data = item;
left = right = null;
}
}
// This code has been contributed by Mayank Jaiswal
執行結果:
Inorder traversal of constructed tree is :
D B E A F C
https://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/