LeetCode 99. 恢复二叉搜索树

99. 恢复二叉搜索树

Difficulty: 困难

给你二叉搜索树的根节点 root ,该树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。

进阶:使用 O(n) 空间复杂度的解法很容易实现。你能想出一个只使用常数空间的解决方案吗?

示例 1:

输入:root = [1,3,null,null,2]
输出:[3,1,null,null,2]
解释:3 不能是 1 左孩子,因为 3 > 1 。交换 1 和 3 使二叉搜索树有效。

示例 2:

输入:root = [3,1,4,null,null,2]
输出:[2,1,4,null,null,3]
解释:2 不能在 3 的右子树中,因为 2 < 3 。交换 2 和 3 使二叉搜索树有效。

提示:

  • 树上节点的数目在范围 [2, 1000]
  • -2<sup>31</sup> <= Node.val <= 2<sup>31</sup> - 1

Solution

Language: 全部题目

对树做一次中序遍历就能找到两个位置不正确的两个节点,解法参考:Python easy to understand solutions - LeetCode Discuss

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def recoverTree(self, root):
        pre = first = second = None
        stack = []
​
        while True:
            while root:
                stack.append(root)  # append的是root节点而不是root.left
                root = root.left
            if not stack:
                break
            node = stack.pop()
            if not first and pre and pre.val > node.val:  # 当第一个节点first找到之后这个if条件便不再满足了
                first = pre
            if first and pre and pre.val > node.val:
                second = node
            pre = node
            root = node.right
​
        first.val, second.val = second.val, first.val
posted @ 2020-12-02 19:37  swordspoet  阅读(78)  评论(0)    收藏  举报