给你二叉搜索树的根节点 root ,该树中的 恰好 两个节点的值被错误地交换。请在不改变其结构的情况下,恢复这棵树 。
示例 1:
输入:root = [1,3,null,null,2]
输出:[3,1,null,null,2]
解释:3 不能是 1 的左孩子,因为 3 > 1 。交换 1 和 3 使二叉搜索树有效。
示例 2:
输入:root = [3,1,4,null,null,2]
输出:[2,1,4,null,null,3]
解释:2 不能在 3 的右子树中,因为 2 < 3 。交换 2 和 3 使二叉搜索树有效。
# 方法一
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
nodes = []
# 中序遍历二叉树,将遍历的结果保存在list中
def dfs(root):
if not root:
return
dfs(root.left)
nodes.append(root)
dfs(root.right)
dfs(root)
x = None
y = None
pre = nodes[0]
# 扫描遍历的结果,找出可能存在的错误交换节点x和y
for i in range(1,len(nodes)):
if pre.val > nodes[i].val:
y = nodes[i]
if not x:
x = pre
pre = nodes[i]
# 如果x和y不为空,则交换两个节点
if x and y:
x.val, y.val = y.val,x.val
72. Leetcode 99. 恢复二叉搜索树 (二叉搜索树-中序遍历类)
最新推荐文章于 2022-02-14 23:39:52 发布