这题首先是要找出来那2个数有问题。按照中序搜索排列之后,就可以找到哪2个有问题了。之后再遍历一次,将错误的数据恢复过来。代码如下:
# 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.
"""
list1 = []
def midorder(root):
if not root:
return root
if root.left:
midorder(root.left)
list1.append(root.val)
if root.right:
midorder(root.right)
return list1
midorder(root)
for i in range(len(list1) - 1):
if list1[i] > list1[i + 1]:
two1 = list1[i]
break
for i in range(1, len(list1)):
if list1[i] < list1[i - 1]:
two2 = list1[i]
stack3 = [two1, two2]
def change(x, num):
if x.val in stack3:
if x.val == stack3[0]:
x.val = stack3[1]
else:
x.val = stack3[0]
num = num + 1
if num == 2:
return
for i in (x.left, x.right):
if i:
change(i, num)
change(root, 0)