文件: 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, | 英文 | 主页 | 类别: 计算机科学 | 430 次阅读, 22519 次搜索 | 164 个单词
| 浏览 | 博客存档
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 430 次阅读, 22519 次搜索 | 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:
Here's a start:
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 430 次阅读, 22519 次搜索 | 164 个单词 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
猜您喜欢...
- CPU Utilization
- Daily Interview Problem: Longest Substring With K Distinct Characters
- Daily Interview Problem: Merge K Sorted Linked Lists
- Daily Interview Problem: Merge Overlapping Intervals
- Daily Interview Problem: Product of Array Except Self
- Spreadsheet Column Title
- Two-Sum
- Detect Linked List Cycle
- Daily Interview Problem: Distribute Bonuses
- A trick for getting good at coding interviews FASTER
©2006~2024 牛排过熟 - 0.01146 秒 - 1890.055 KB/s - 38 在线 内存: 495.6 KB
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - 服务器 PHP 版本号: 7.4.33
牛排怎么做才好吃? | <meta name="机器人" content="索引, 跟踪">
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - 服务器 PHP 版本号: 7.4.33
评论 (0)
读写完全 - 一般 - 最小 - 表格 - 所有评论 - 统计
当前页暂时没有评论。