We run a preorder depth first search on the root
of a binary tree.
At each node in this traversal, we output D
dashes (where D
is the depth of this node), then we output the value of this node. (If the depth of a node is D
, the depth of its immediate child is D+1
. The depth of the root node is 0
.)
If a node has only one child, that child is guaranteed to be the left child.
Given the output S
of this traversal, recover the tree and return its root
.
Example 1:
Input: "1-2--3--4-5--6--7" Output: [1,2,5,3,4,6,7]
Example 2:
Input: "1-2--3---4-5--6---7" Output: [1,2,5,3,null,6,null,4,null,7]
Example 3:
Input: "1-401--349---90--88" Output: [1,401,null,349,88,90]
Note:
- The number of nodes in the original tree is between
1
and1000
. - Each node will have a value between
1
and10^9
.
思路:自己模拟一遍怎么遍历和建树过程就知道了
遍历过程,每层只会有一个活动的Node(活动的意思是后续可能还要遍历改node的右子树),那我们在建树的过程就维护一个stack(因为是先序遍历),stack的index表示depth,value用tuple表示,第一个值表示当前depth下的node,第二个值表示左子树是不是已经建树完成了
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def recoverFromPreorder(self, S):
"""
:type S: str
:rtype: TreeNode
"""
if '-' not in S: return TreeNode(int(S))
p=S.index('-')
res=TreeNode(int(S[:p]))
depth=[[res,False]] # one depth, one node during traversal, use one flag to mark whether left has been set
while p<len(S):
d=0
while S[p]=='-':
d+=1
p+=1
q=p
while q<len(S) and S[q]!='-': q+=1
v = int(S[p:q])
p=q
child = TreeNode(v)
while len(depth)!=d:
depth.pop()
if depth[d-1][1]:
depth[d-1][0].right = child
else:
depth[d-1][0].left = child
depth[d-1][1] = True
depth.append([child,False])
return res