问题描述
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?
解题思路
恢复二叉搜索树很容易想到中序遍历。这里把每个节点以及节点的值通过中序遍历分别保存到vec1和vec2中,然后对存有节点值的vec2进行排序,最后再将vec2中每个值逐个赋给vec1中的相应节点即可
代码如下
class Solution { public: void recoverTree(TreeNode* root) { if (root == NULL) return; vector<TreeNode*> list; vector<int> vec; inorder(root, list, vec); int leng = vec.size(); sort(vec.begin(), vec.end()); for (int i = 0; i < leng; i++) { list[i]->val = vec[i]; } } void inorder(TreeNode *root, vector<TreeNode*> &list, vector<int> &vec) { if (root == NULL) return; inorder(root->left, list, vec); vec.push_back(root->val); list.push_back(root); inorder(root->right, list, vec); } };