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

Subscribe to Feed Burner | Browse | Archive
Hi, here's your problem today. This problem was recently asked by Microsoft:

You are given the preorder and inorder traversals of a binary tree in the form of arrays. Write a function that reconstructs the tree represented by these traversals.

Example:
Preorder: [a, b, d, e, c, f, g]
Inorder: [d, b, e, a, f, c, g]

The tree that should be constructed from these traversals is:


a
/ \
b c
/ \ / \
d e f g


Here's a start:


from collections import deque

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

def __str__(self):
q = deque()
q.append(self)
result = ''
while len(q):
n = q.popleft()
result += n.val
if n.left:
q.append(n.left)
if n.right:
q.append(n.right)

return result


def reconstruct(preorder, inorder):
# Fill this in.

tree = reconstruct(['a', 'b', 'd', 'e', 'c', 'f', 'g'],
['d', 'b', 'e', 'a', 'f', 'c', 'g'])
print tree
# abcdefg
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Cateogry: Computing | 124 Views, 15932 Search Bots | 164 Words Subscribe to Feed Burner

Related Articles

  1. [Daily Problem] Validate Balanced Parentheses
  2. Daily Interview Problem: Jump to the End
  3. Spreadsheet Column Title
  4. Daily Interview Problem: Find the k-th Largest Element in a List
  5. Sort a Partially Sorted List
  6. Number of Ways to Climb Stairs
  7. Consecutive Ones
  8. Algorithm Interview Question: Find the Single Element in an Array of Duplicates
  9. Daily Interview Problem: Contiguous Subarray with Maximum Sum
  10. Sorting a list with 3 unique numbers

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" />