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

定阅此目录的博客 | 浏览 | 博客存档
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
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 124 次阅读, 15610 次搜索 | 164 个单词 定阅此目录的博客

猜您喜欢...

  1. Daily Interview Problem: Find the k-th Largest Element in a List
  2. Daily Interview Problem: Jump to the End
  3. Batch Programming in XP
  4. Spreadsheet Columns
  5. Reverse a Linked List
  6. First and Last Indices of an Element in a Sorted Array
  7. Daily Interview Problem: Arithmetic Binary Tree
  8. Binary Tree Level with Minimum Sum
  9. Daily Interview Problem: Given two arrays, write a function to compute their intersection.
  10. Daily Interview Problem: Maximum Profit From Stocks

评论 (0)

    当前页暂时没有评论。


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