Skip to content

Instantly share code, notes, and snippets.

@rsofaer
Last active December 30, 2015 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save rsofaer/7779662 to your computer and use it in GitHub Desktop.
Save rsofaer/7779662 to your computer and use it in GitHub Desktop.
Hint file for postfix to infix
class TreeNode
attr_accessor :val, :left, :right
def initialize(v)
@val = v
end
def leaf?
# A node is a leaf if it has no children.
end
end
def numeric?(str)
true if Float(str) rescue false
end
def parse_postfix_expression(exp)
# Split our arithmetic expression at the whitespaces.
tokens = exp.split(/\s/)
# Since we are parsing postfix, the root node will always be the last token.
return get_next_node(tokens)
end
def get_next_node(tokens)
# The next token will be the root of the tree we are building.
# If we are a number node, we are a leaf, so skip this.
# The second token will be the beginning of the right subtree.
# After the right subtree will come the left subtree.
end
data = File.read("data").split("\n").map {|l| parse_postfix_expression(l)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment