Problem
You are given the root of a binary search tree (BST), where exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
Follow up: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
Algorithm
Save the data in a list, sort and restore.
Code
# 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: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
index = 0
pL = []
nL = []
def travel(root):
if root.left:
travel(root.left)
pL.append(root)
nL.append(root.val)
if root.right:
travel(root.right)
travel(root)
nL.sort()
for i in range (len(pL)):
pL[i].val = nL[i]
这篇博客讨论了一种算法,用于恢复一个二叉搜索树,该树中有两个节点因错误被交换。算法首先遍历树并保存节点值,然后对值进行排序并重新赋值给节点,从而恢复BST的正确结构。这是一个O(n)空间复杂度的解决方案,挑战在于如何设计常数空间的解决方案。
3352

被折叠的 条评论
为什么被折叠?



