[leetcode]971. Flip Binary Tree To Match Preorder Traversal

Flip Binary Tree To Match Preorder Traversal

这是一个结合了先序遍历和对边界检查的题。刚开始理不太清楚,我就简单画了一下几种情况的图。
所有情况如下:

  1. 当前结点被访问过
  • 当前结点是叶结点
  • 当前结点只有左树
  • 当前结点只有右子树
  • 当前结点有两个子树(这种情况不会出现)
  1. 当前结点没有被访问过
  • 当前结点是叶结点
  • 当前结点只有左树
  • 当前结点只有右子树
  • 当前结点有两个子树
    • 左子树的值和 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值