LeetCode99题
思路:比较笨。。。自己做的,只想出来了一种,将所有数据提取,排序,然后中序遍历重新赋值。。时间空间都不咋地的算法。。
后来看网友的做了一点改进,中序遍历,正常情况都是递增的,如果反常则记录该情况。
# 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: None Do not return anything, modify root in-place instead.
"""
x = y = pre = None
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if pre and root.val < pre.val:
y = root
if x is None:
x = pre
else:
break
pre = root
root = root.right
x.val, y.val = y.val, x.val