页面顶部 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 次阅读, 15617 次搜索 | 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 次阅读, 15617 次搜索 | 164 个单词 定阅此目录的博客

猜您喜欢...

  1. Consecutive Ones
  2. [Daily Problem] Course Prerequisites
  3. Daily Interview Problem: Largest BST in a Binary Tree
  4. Palindrome Integers
  5. [Daily Problem] Remove Consecutive Nodes that Sum to 0
  6. Daily Interview Question: Create a Simple Calculator
  7. Daily Interview Problem: Contiguous Subarray with Maximum Sum
  8. Plus One
  9. Daily Interview Problem: Min Stack
  10. Daily Interview Problem: 3 Sum

评论 (0)

    当前页暂时没有评论。


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