我们从二叉树的根节点 root?开始进行深度优先搜索。
在遍历中的每个节点处,我们输出?D?条短划线(其中?D?是该节点的深度),然后输出该节点的值。(如果节点的深度为 D,则其直接子节点的深度为 D + 1。根节点的深度为 0)。
如果节点只有一个子节点,那么保证该子节点为左子节点。
给出遍历输出?S,还原树并返回其根节点?root。
?
示例 1:
输入:"1-2--3--4-5--6--7"
输出:[1,2,5,3,4,6,7]
示例 2:
输入:"1-2--3---4-5--6---7"
输出:[1,2,5,3,null,6,null,4,null,7]
示例 3:
输入:"1-401--349---90--88"
输出:[1,401,null,349,88,90]
?
提示:
原始树中的节点数介于 1 和 1000 之间。
每个节点的值介于 1 和 10 ^ 9 之间。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/recover-a-tree-from-preorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getLRTree(self, slist):
leftn = None
rightn = None
if len(slist) == 2:
leftn = TreeNode(slist[1])
return leftn, rightn
elif len(slist) == 0:
return leftn, rightn
level_s = slist[0]
second_s = 0
str1=‘‘
str2=‘‘
#print(slist)
for i in range(1, len(slist)):
if slist[i] == level_s:
second_s = i
break
if second_s != 0:
str1 = slist[2:second_s]
str2 = slist[second_s + 2 :]
rightn = TreeNode(slist[second_s+1])
rightn_l, rightn_r = self.getLRTree(str2)
rightn.left = rightn_l
rightn.right = rightn_r
else:
str1 = slist[2:]
leftn = TreeNode(slist[1])
leftn_l, leftn_r = self.getLRTree(str1)
leftn.left = leftn_l
leftn.right = leftn_r
return leftn, rightn
def recoverFromPreorder(self, S: str) -> TreeNode:
split_list = []
tmp_str = ‘‘
store = False
for i in range(len(S)):
tmp_str += S[i]
if i == len(S) - 1:
split_list.append(tmp_str)
break
if (S[i] != ‘-‘ and S[i+1] == ‘-‘) or (S[i] == ‘-‘ and S[i+1] != ‘-‘):
split_list.append(tmp_str)
tmp_str = ‘‘
root = TreeNode(split_list[0])
leftn, rightn = self.getLRTree(split_list[1:])
root.left = leftn
root.right = rightn
# print out
result_queue = [root]
result_list = []
while len(result_queue) > 0:
tmp_n = result_queue.pop(0)
if not tmp_n:
result_list.append(‘null‘)
continue
result_list.append(tmp_n.val)
result_queue.append(tmp_n.left)
result_queue.append(tmp_n.right)
return root
[Notes] 2020.6.18 每日一题 从先序遍历还原二叉树
原文:https://www.cnblogs.com/immortalBlog/p/13156974.html