{
  "type": "code_options",
  "author": "csdn.net",
  "source": "solution.md",
  "exercise_id": "51c26bca89994c5ba6ce2432f84304ee",
  "keywords": "树,深度优先搜索,二叉搜索树,二叉树",
  "title": "恢复二叉搜索树",
  "desc": [
    {
      "content": "\n<p>给你二叉搜索树的根节点 <code>root</code> ，该树中的两个节点被错误地交换。请在不改变其结构的情况下，恢复这棵树。</p><p><strong>进阶：</strong>使用 O(<em>n</em>) 空间复杂度的解法很容易实现。你能想出一个只使用常数空间的解决方案吗？</p><p> </p><p><strong>示例 1：</strong></p><img alt=\"\" src=\"https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover1.jpg\" style=\"width: 422px; height: 302px;\" /><pre><strong>输入：</strong>root = [1,3,null,null,2]<strong><br />输出：</strong>[3,1,null,null,2]<strong><br />解释：</strong>3 不能是 1 左孩子，因为 3 > 1 。交换 1 和 3 使二叉搜索树有效。</pre><p><strong>示例 2：</strong></p><img alt=\"\" src=\"https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0099.Recover%20Binary%20Search%20Tree/images/recover2.jpg\" style=\"width: 581px; height: 302px;\" /><pre><strong>输入：</strong>root = [3,1,4,null,null,2]<strong><br />输出：</strong>[2,1,4,null,null,3]<strong><br />解释：</strong>2 不能在 3 的右子树中，因为 2 < 3 。交换 2 和 3 使二叉搜索树有效。</pre><p> </p><p><strong>提示：</strong></p><ul>\t<li>树上节点的数目在范围 <code>[2, 1000]</code> 内</li>\t<li><code>-2<sup>31</sup> <= Node.val <= 2<sup>31</sup> - 1</code></li></ul>",
      "language": "markdown"
    }
  ],
  "answer": [
    {
      "content": "",
      "language": "java"
    }
  ],
  "prepared": [
    [
      {
        "content": "",
        "language": "java"
      }
    ],
    [
      {
        "content": "",
        "language": "java"
      }
    ],
    [
      {
        "content": "",
        "language": "java"
      }
    ]
  ],
  "template": {
    "content": "public class TreeNode {\n\tint val;\n\tTreeNode left;\n\tTreeNode right;\n\n\tTreeNode() {\n\t}\n\n\tTreeNode(int val) {\n\t\tthis.val = val;\n\t}\n\n\tTreeNode(int val, TreeNode left, TreeNode right) {\n\t\tthis.val = val;\n\t\tthis.left = left;\n\t\tthis.right = right;\n\t}\n}\n\nclass Solution {\n\tTreeNode t1, t2, pre;\n\n\tpublic void recoverTree(TreeNode root) {\n\t\tinorder(root);\n\t\tint temp = t1.val;\n\t\tt1.val = t2.val;\n\t\tt2.val = temp;\n\t}\n\n\tpublic void inorder(TreeNode root) {\n\t\tif (root == null)\n\t\t\treturn;\n\t\tinorder(root.left);\n\t\tif (pre != null && pre.val > root.val) {\n\t\t\tif (t1 == null)\n\t\t\t\tt1 = pre;\n\t\t\tt2 = root;\n\t\t}\n\t\tpre = root;\n\t\tinorder(root.right);\n\t}\n}",
    "language": "java"
  },
  "node_id": "dailycode-77a803dcb98440b7a136a24276b6854d",
  "license": "csdn.net",
  "created_at": 1637894158,
  "topic_link": "https://bbs.csdn.net/topics/600470826"
}