Parsing and building S-Expressions using Sets and binary search tree

别说谁变了你拦得住时间么 提交于 2019-12-04 21:29:12

Dijkstra has done it for you already :-)

Try the shunting yard algorithm: http://en.wikipedia.org/wiki/Shunting-yard_algorithm

You can create the RPN (reverse polish notation) using the shunting yard algorithm, and once that is created, you can make a pass through it to create the binary tree.

Normally, the RPN is used to do the evaluation, but you can actually create a tree.

For instance, instead of evaluating, you create tree nodes and push them onto the stack.

So if you see node1, node2 , operator. You create a new node

   Operator
   /     \
  node1   node2

and push it back onto the stack.

A more detailed example:

Say the expression is (apples AND oranges) OR kiwis

THe RPN for this is kiwis oranges apples AND OR

Now walk this while maintaining a stack.

Make a node out of kiwis push onto stack. Node out of oranges push onto stack. Same with apples.

So The stack is

Node:Apples
Node:Oranges
Node:Kiwis

Now you see the AND in the RPN.

You pop the top two from the stack and create a new Node with AND as parent.

Node:AND, [Node:Apples, Node:Oranges]

basically the tree

       AND
     /    \
  Apples  Oranges

Now push this node onto stack.

So stack is

Node:AND, [Node:Apples, Node:Oranges]
Node:Kiwis

Now you see the OR in the RPN and create a node with OR as parent and Node:ANd and Node Kiwis as children getting the tree

           OR 
         /   \
       AND   Kiwis
     /    \
  Apples  Oranges

You might even be able to modify the shunting yard algorithm to create the tree, but dealing with the RPN seems easier.

Alternately, you can try using Recursive Descent Parsing techniques. What you ask is very common and you will be able to find grammars and code even, if you search the web.

By the way, you just mean Binary tree right? BST (Binary Search Tree) has an extra constraint...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!