Question

I have a parse tree that parses out a stack of a stack of char (stack<stack<char>>). This gets the characters into a parse tree. My question is how would I convert this parse tree into a AST in order to evaluate it?

I have the evaluator working for a AST I just need to convert the tree into the syntax in order to evaluate it.

Any help would be appreciated.

Here is a picture of what I am trying to accomplish

Was it helpful?

Solution

I was able to convert them using a Tree Traversal Algorithm

Using Pre Order Traversal

preorder(node)
  if node == null then return
  print node.value
  preorder(node.left) 
  preorder(node.right)

Using a stack to store the leaf nodes I added the values onto them and was able to transverse the stack and change into lea nodes.

A example for 10 + 4

the parse tree leafs using preorder would give me a stack of [+ 10 4]

Using a helper function I could convert this into a

Make_Plus(Make_Int(10), Make_Int(4)) by using recursion

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top