LeetCode #99: Recover Binary Search Tree

129 篇文章 0 订阅

Problem Statement

(Source) Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure.

Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

Analysis

Think of the in-order traversal sequence of a binary search tree. It is an increasing sequence. If two elements of the original binary search tree are swapped, then the new in-order traversal sequence would not be in ascending order anymore, but it must fit into one of the following two cases:
(1) There exists only one pair of elements (seq[i], seq[i + 1]) in the new sequence such that seq[i] > seq[i + 1].
(2) There exists two pairs of elements (seq[i], seq[i + 1]), (seq[j], seq[j + 1]) in the new sequence such that seq[i] > seq[i + 1] && seq[j] > seq[j + 1].

Therefore, the idea to solve the problem is to find the first node corresponding to the first element of the first pair, and the last node corresponding to the last element of the last pair, no matter which case the new sequence fits into, and swap them.

Solution below uses an recursive implementation below, which runs in:
- Time complexity: O(n), where n is the total number of the binary search tree.
- Space complexity: O(1).

Solution

# 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 recoverTree(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """
        swapped_nodes = []
        prev = [None]

        def inorder(p, prev, swapped_nodes):
            if p.left:
                inorder(p.left, prev, swapped_nodes)

            if prev[0] and prev[0].val > p.val:
                if len(swapped_nodes) == 0:
                    swapped_nodes.extend([prev[0], p])
                else:
                    swapped_nodes[1] = p
            prev[0] = p

            if p.right:
                inorder(p.right, prev, swapped_nodes)

        inorder(root, prev, swapped_nodes)

        swapped_nodes[0].val, swapped_nodes[1].val = swapped_nodes[1].val, swapped_nodes[0].val
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值