页面顶部 Top
文件:  root - text - article - 2019 - 12 - arithmetic-binary-tree.txt
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 304 次阅读, 14876 次搜索 | 142 个单词

定阅此目录的博客 | 浏览 | 博客存档
Hi, here's your problem today. This problem was recently asked by Apple:

You are given a binary tree representation of an arithmetic expression. In this tree, each leaf is an integer value,, and a non-leaf node is one of the four operations: '+', '-', '*', or '/'.

Write a function that takes this tree and evaluates the expression.

Example:


*
/ \
+ +
/ \ / \
3 2 4 5


This is a representation of the expression (3 + 2) * (4 + 5), and should return 45.

Here's a starting point:


class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right

PLUS = "+"
MINUS = "-"
TIMES = "*"
DIVIDE = "/"

def evaluate(root):
# Fill this in.

tree = Node(TIMES)
tree.left = Node(PLUS)
tree.left.left = Node(3)
tree.left.right = Node(2)
tree.right = Node(PLUS)
tree.right.left = Node(4)
tree.right.right = Node(5)
print evaluate(tree)
# 45
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 304 次阅读, 14876 次搜索 | 142 个单词 定阅此目录的博客

猜您喜欢...

  1. Spectrum Master
  2. Most Frequent Subtree Sum
  3. Longest Substring Without Repeating Characters
  4. [Daily Problem] Angles of a Clock
  5. [Daily Problem] Remove k-th Last Element From Linked List
  6. Daily Interview Puzzle: Falling Dominoes
  7. ImageMagick Vulnerabilities -  CVE-2016–3714
  8. Patterns for breaking down questions you haven
  9. Daily Interview Problem: Word Ordering in a Different Alphabetical Order
  10. Generate All IP Addresses

评论 (0)

    当前页暂时没有评论。


最后更新: October 30 2020 14:21:12 | RSS Subscription
牛排怎么做才好吃? | <meta name="机器人" content="索引, 跟踪">