LeetCode 99. 恢复二叉搜索树

Description

二叉搜索树中的两个节点被错误地交换。

请在不改变其结构的情况下,恢复这棵树。

示例 1:

输入: [1,3,null,null,2]

   1
  /
 3
  \
   2

输出: [3,1,null,null,2]

   3
  /
 1
  \
   2
示例 2:

输入: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

输出: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/recover-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Solution

题解

# 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.
        """

        def _inorder(root):
            if not root: return
            # 遍历左子树
            _inorder(root.left)
            
            nonlocal pre, nodes
            if pre and pre.val > root.val:  # 记录当前的逆序对
                nodes.append(pre)
                nodes.append(root)
            pre = root
            # 遍历右子树
            _inorder(root.right)

        pre = None
        nodes = []
        _inorder(root)
        if len(nodes) == 2:
            i, j = 0, 1
        elif len(nodes) == 4:
            i, j = 0, 3
        else:
            return

        nodes[i].val, nodes[j].val = nodes[j].val, nodes[i].val
        return

作者:dz-lee
链接:https://leetcode-cn.com/problems/recover-binary-search-tree/solution/zhong-xu-bian-li-chang-liang-kong-jian-fu-za-du-py/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(LeetCode,算法----二叉树)