文件: 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, | 英文 | 主页 | 类别: 计算机科学 | 207 次阅读, 19389 次搜索 | 164 个单词
| 浏览 | 博客存档
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 207 次阅读, 19389 次搜索 | 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, | 英文 | 主页 | 类别: 计算机科学 | 207 次阅读, 19389 次搜索 | 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
猜您喜欢...
- Absolute Path
- New Vulnerabilities (CVE-2016-4581) have been detected in CentOS/RHEL/CloudLinux 7
- Making a Height Balanced Binary Search Tree
- Reverse a Directed Graph
- PHP Unit Tests on VPS Server
- Daily Interview Question: Word Search
- Patterns for breaking down questions you haven
- Daily Interview Problem: Merge Overlapping Intervals
- Daily Interview Problem: Longest Substring With K Distinct Characters
- Daily Interview Problem: Given two arrays, write a function to compute their intersection.
©2006~2024 牛排过熟 - 0.02483 秒 - 813.56 KB/s - 61 在线 内存: 496.2 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)
读写完全 - 一般 - 最小 - 表格 - 所有评论 - 统计
当前页暂时没有评论。