Search code examples
c++data-structurestreebinary-treeexpression-trees

convert short form of tree string(parentheses) into full form


I want to convert a short form of a tree string expression (with parentheses) into the full form of it.

This is an example tree expression:

intput: ((((XX(XXX(XX 
output: ((((XX)(XX))X)(XX))

and this tree looks like:
this.

can some one provides me full code or at least some part of code in C++?

other example:

input: (S((SS(S(S(((S(SSSS 

output: (S((SS)(S(S(((S(SS))S)S)))))

Solution

  • It is an inorder tree traversal process. Root-->Left-->Right.

    If you want I can write the full solution which will take some time.

    Can You give me an example code(I mean is there any code snippets given)? Or I have to write tree-building code and then output?

    look at you code: Let answer string = "";

    step 01: root -->(, answer = "(", go left

    step02: root --->(, answer = "((", go left

    step 03: root -->( answer = "(((", go left

    step04: root --> ( answer = "((((, go left

    step 05: root ---> x answer = "((((x, there is no left, go right of step 04

    step 06: root--> x, answer = "((((xx, there is no left, right, so add ")"

    so the answer will be = "((((xx), and go right of step 03

    step 07: root -->(, answer = "(((xx)(, go left

    step 08: root--> x answer = "((((xx)(x, no left go right of step 07

    step 09: root--> x answer = "((((xx)(xx, there is no left or right , go back, add")"

    so the answer will be= "((((xx)(xx)

    same way you can solve the rest of the tree.

    Note If there is no child node, and the node is right of parent node add ")"(closing bracket)