又是一道二叉树的题目,核心还是想清楚递归和迭代的问题。
之前我们做过还原二叉树的题目,那道题目的是给出了中序遍历和前(后)序遍历,实现还原。简单复习一下那道题目的思想。利用了中序遍历的特点,把前后序遍历一分为二,递归解决。
这道题目,给出的条件实际上是先序遍历,和每个节点对应的深度,并且给出了假设,如果只有一个节点就一定是左节点。
因此我们就按照先序遍历的方法,依次构建左节点并存入一个列表,列表对应的索引其实相当于是深度,然后如果当前节点的深度小于栈的索引,弹出元素到栈顶元素索引+1==深度
,构建右节点。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def recoverFromPreorder(self, S: str) -> TreeNode:
path, i = [], 0
while i<len(S):
# 统计节点的深度
dep = 0
while S[i] == '-':
dep += 1
i += 1
# 得到节点的数值
val = 0
while i<len(S) and S[i].isdigit():
val = val*10 + int(S[i])
i += 1
node = TreeNode(val)
# 如果深度等于栈顶元素的索引,添加左节点,否则右节点
if dep == len(path):
if path:
path[-1].left = node
else:
path = path[:dep]
path[-1].right = node
path.append(node)
return path[0]