To the Top
File:  root - text - article - 2019 - 12 - arithmetic-binary-tree.txt
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Category: Computing | 304 Views, 15127 Search Bots | 142 Words

Subscribe to Feed Burner | Browse | Archive
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
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Cateogry: Computing | 304 Views, 15127 Search Bots | 142 Words Subscribe to Feed Burner

Related Articles

  1. Daily Interview Problem: Full Binary Tree
  2. Daily Interview Problem: Get all Values at a Certain Height in a Binary Tree
  3. Algorithm Interview Question: Max and Min with Limited Comparisons
  4. [Daily Problem] Move Zeros
  5. Maximum In A Stack
  6. Kaprekar
  7. Binary Tree Level with Minimum Sum
  8. Fibonacci coding
  9. [Daily Problem] Witness of The Tall People
  10. Daily Interview Problem: First Missing Positive Integer

Comments (0)

Your Email (Domain Part Not Exposed):

Your Comments:

Privately By Mail Colors More Smileys S x y @

Verification (Click Image 2 Refresh):

    Be the first one to comment this page !


Page Edited: October 30 2020 14:21:09 | RSS Subscription
How to Cook a Perfect Steak? | <meta name="robots" content="noindex, follow" />