0

I have a tree data structure, comprised of nodes, that I need to parse into an expression tree. My nodes look like this (simplified):

    public class Node
    {
        public Node Left { get; set; }
        public Node Right { get; set; }
        public Operation OperationType { get; set; }
        public object Value { get; set; }
    }

What is the best / correct way to find the bottom of the tree and work backwards building up the expression tree? Do you parse left or right first?

2
  • 1
    Can you provide an example of the desired output? Commented Jun 15, 2009 at 22:47
  • It is not clear to me if you want to parse a string representation to the tree or if you want to evaluate the tree once you have already parsed it. Commented Jun 15, 2009 at 22:53

3 Answers 3

1

If you want to get to the bottom of the tree first, then you do an 'in-order' or perhaps 'post-order' search. An 'in-order' search will find the bottom, left-most node first, followed by the parent of that node, and then the right-hand child of the parent. A 'post-order' search will 'visit' both the left child node and the right child node before visiting the parent node.

Consider the expression 'x + y'. An in-order search would yield:

'x', '+', 'y'

whereas an post-order search would yield:

'x', 'y', '+'
Sign up to request clarification or add additional context in comments.

Comments

1

As mentioned, it doesn't really matter where you go first. But the most usual tree traversal algorithms. If this tree is organized the way I think, inorder would be recommended:

(from wikipedia)To traverse a non-empty binary tree in inorder, perform the following operations recursively at each node:

  1. Traverse the left subtree.
  2. Visit the root.
  3. Traverse the right subtree.

(This is also called Symmetric traversal.)

Comments

0

I don't think it matters which direction you traverse first. However, in a world where left-to-right language dominates, someone would more intuitively understand your code if you went left first.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.