[Leetcode]Recover Binary Search Tree

22 篇文章 0 订阅
10 篇文章 0 订阅

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?

一颗二叉查找树的两个节点调换了,要求恢复这颗二叉查找树~BST有一个性质,就是它的中序遍历是有序的,可以根据这个性质来做~要注意考虑有两种情况:如果是相邻的节点被调换了,那么就只出现一次逆序;如果调换的两个节点不相邻,就会出现两次逆序;用first, second来记录两个交换了的节点;

下面代码是根据中序遍历的非递归解法写的~这种解法时间复杂度为O(n),空间复杂度为O(logn)~

class Solution:
    # @param root, a tree node
    # @return a tree node
    def recoverTree(self, root):
        if root is None: return None
        pre, first, second, stack, cur = None, None, None, [], root
        while stack or cur:
            if cur:
                stack.append(cur)
                cur = cur.left
            else:
                cur = stack.pop()
                if pre and pre.val > cur.val:
                    if first is None:
                        first, second = pre, cur
                    else:
                        second = cur
                pre, cur = cur, cur.right
        first.val, second.val = second.val, first.val
        return root


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值