Flip Binary Tree To Match Preorder Traversal
这是一个结合了先序遍历和对边界检查的题。刚开始理不太清楚,我就简单画了一下几种情况的图。
所有情况如下:
- 当前结点被访问过
- 当前结点是叶结点
- 当前结点只有左树
- 当前结点只有右子树
- 当前结点有两个子树(这种情况不会出现)
- 当前结点没有被访问过
- 当前结点是叶结点
- 当前结点只有左树
- 当前结点只有右子树
- 当前结点有两个子树
- 左子树的值和 voyage 的第一个元素的值相同
- 左子树的值和 voyage 的第一个元素的值不同
处理好上面的情况就解决了这个问题。
# 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 flipMatchVoyage(self, root, voyage):
"""
:type root: TreeNode
:type voyage: List[int]
:rtype: List[int]
"""
res = []
stack = [root]
while stack and voyage:
stop = stack[-1]
if stop.val == -1:
if stop.left is None and stop.right is None:
stack.pop()
continue
if stop.left:
stack.append(stop.left)
stop.left = None
continue
if stop.right:
stack.append(stop.right)
stop.right = None
continue
# if left and right exist
# stack top not visited.
vtop = voyage.pop(0)
if stop.val != vtop:
return [-1]
tmp = stop.val
stop.val = -1
if stop.left is None and stop.right is None:
stack.pop()
continue
if stop.right is None:
stack.append(stop.left)
stop.left = None
continue
if stop.left is None:
stack.append(stop.right)
stop.right = None
continue
if not voyage:
return [-1]
val = voyage[0]
if val == stop.left.val:
stack.append(stop.left)
stop.left = None
continue
res.append(tmp)
stack.append(stop.right)
stop.right = None
while stack and stack[-1].left is None and stack[-1].right is None and stack[-1].val == -1:
stack.pop()
if stack or voyage:
return [-1]
return res