{ "type": "code_options", "author": "https://github.com/begeekmyfriend/leetcode", "source": "solution.md", "exercise_id": "c360ad96980d4503a5e1bc0b1865971b", "keywords": "树,深度优先搜索,二叉搜索树,二叉树", "title": "恢复二叉搜索树", "desc": [ { "content": "\n

给你二叉搜索树的根节点 root ,该树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。

进阶:使用 O(n) 空间复杂度的解法很容易实现。你能想出一个只使用常数空间的解决方案吗?

 

示例 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 使二叉搜索树有效。

 

提示:

", "language": "markdown" } ], "answer": [ { "content": "", "language": "cpp" } ], "prepared": [ [ { "content": "", "language": "cpp" } ], [ { "content": "", "language": "cpp" } ], [ { "content": "", "language": "cpp" } ] ], "template": { "content": "#include \nusing namespace std;\nstruct TreeNode\n{\n\tint val;\n\tTreeNode *left;\n\tTreeNode *right;\n\tTreeNode() : val(0), left(nullptr), right(nullptr) {}\n\tTreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n\tTreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n};\nclass Solution\n{\npublic:\n\tvoid recoverTree(TreeNode *root)\n\t{\n\t\tdfs(root);\n\t\tint tmp = p0_->val;\n\t\tp0_->val = p1_->val;\n\t\tp1_->val = tmp;\n\t}\nprivate:\n\tint wrong_ = 0;\n\tTreeNode *prev_ = nullptr;\n\tTreeNode *p0_ = nullptr;\n\tTreeNode *p1_ = nullptr;\n\tvoid dfs(TreeNode *root)\n\t{\n\t\tif (root == nullptr || wrong_ == 2)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tdfs(root->left);\n\t\tif (prev_ != nullptr && prev_->val > root->val)\n\t\t{\n\t\t\tif (++wrong_ == 1)\n\t\t\t{\n\t\t\t\tp0_ = prev_;\n\t\t\t\tp1_ = root;\n\t\t\t}\n\t\t\telse if (wrong_ == 2)\n\t\t\t{\n\t\t\t\tp1_ = root;\n\t\t\t}\n\t\t}\n\t\tprev_ = root;\n\t\tdfs(root->right);\n\t}\n};", "language": "cpp" }, "node_id": "dailycode-22d0c66ac13e492ab38799ba4281480b", "license": "csdn.net", "created_at": 1637894158, "topic_link": "https://bbs.csdn.net/topics/600470826" }