恢复二叉搜索树
程序员文章站
2022-06-17 19:46:52
...
Python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
cur, pre = root, None
first, second = None, None
stack = []
while cur or stack:
if cur:
stack.append(cur)
cur = cur.left
else:
node = stack.pop()
if pre and pre.val >= node.val:
if not first:
first = pre
second = node
pre = node
cur = node.right
first.val, second.val = second.val, first.val
上一篇: 查找中位数(分治策略)
下一篇: 买卖股票的最佳时机 II