Construct a Tree

后端 未结 2 1114
醉梦人生
醉梦人生 2020-12-18 07:33

How can I construct a tree given its inorder and preorder traversal? I am just looking for an efficient algorithm.

2条回答
  •  误落风尘
    2020-12-18 08:22

    A blatant copy and paste from Sun's (Oracle now, I guess...) forum:

    Question:
    Can anybody help me on how to construct Binary tree from inorder and postorder traversals,i just want to know the algorithm so that i can apply it.

    Answer:
    Let p_1, p_2 ... p_n be the postorder traversal and let i_1, i_2 ... i_n be the inorder traversal. From the postorder traversal we know that the root of the tree is p_n. Find this element in the inorder traversal, say i_1, i_2 ... i_k-1 p_n i_k+1 ... i_n. From the inorder traversal we find all the elements in the left subtree, i.e. i_1, i_2 ... i_k-1 and in the right subtree, i.e. i_k+1 ... i_n respectively.

    Remove element p_n (and element i_k == p_n). Find the rightmost element p_j in p_1, p_2 ... p_j ... p_n-1 where p_j is an element in i_1, i_2 ... i_k-1. This is the root of the left subtree of the original tree. Split p_1, p_2 ... p_j and p_j+1 ... p_n-1 and i_1, i_2 ... i_k-1 and i_k+1 ... i_n. Now you have two subsequences representing the postorder and inorder traversal of the two subtrees of the original tree.

    Author: JosAH.

    I've implemented the algorithm once following Jos' instructions, and it worked perfectly!

提交回复
热议问题