Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
=============
解法:来自leetcode 150题集
O(n)的解法,开一个指针数组,中序遍历,将节点指针一次存放在数组中,
然后寻找两处逆向的位置,先从前往后找第一个逆序的位置,然后从后往前寻找第二个逆序的位置,交换两个指针的值,
递归/非递归中序遍历一般需要用到栈,空间也是O(n)的,可以利用morris中序遍历的方式
=====
code:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: /// void recoverTree(TreeNode *root){ pair<TreeNode *,TreeNode *> broken; TreeNode *curr = root; TreeNode *prev = nullptr; broken.first = broken.second = nullptr; while(curr!=nullptr){ if(curr->left==nullptr){ detect(broken,prev,curr); prev = curr; curr = curr->right; }else{ auto node = curr->left; ///prev = curr->left; while(node->right != nullptr && node->right!=curr){ node = node->right; } ///find predecessor if(node->right==nullptr){ node->right = curr; curr = curr->left; }else{ node->right = nullptr; detect(broken,prev,curr); prev = curr; curr = curr->right; } }///if-else }///while swap(broken.first->val,broken.second->val); } void detect(pair<TreeNode *,TreeNode *> &broken,TreeNode *prev, TreeNode *curr){ if(prev!=nullptr && prev->val > curr->val){ if(broken.first == nullptr) broken.first = prev; broken.second = curr; } } };
时间: 2024-11-07 02:04:18