Created
September 23, 2018 04:17
-
-
Save woodRock/9e1fcb594076fed58d53873e01d4b8b6 to your computer and use it in GitHub Desktop.
Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one of '+', '−', '∗', or '/'. Given the root to such a tree, write a function to evaluate it. For example, given the following tree: * / \ + + / \ / \ 3 2 4 5 You should return 45, as it is (3 + 2) * (4 + 5).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
class Node | |
attr_accessor :val, :left, :right | |
def initialize val, left=nil, right=nil | |
@val = val | |
@left = left | |
@right = right | |
end | |
end | |
def in_order(node) | |
str = "" | |
if not node.nil? | |
str += "(" if not node.left.nil? | |
str += in_order(node.left) | |
str += node.val | |
str += in_order(node.right) | |
str += ")" if not node.right.nil? | |
end | |
return str | |
end | |
left = Node.new('+', Node.new('3'), Node.new('2')) | |
right = Node.new('+', Node.new('4'), Node.new('5')) | |
root = Node.new('*', left, right) | |
puts eval(in_order(root)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment