首页 > 代码库 > Recover Binary Search Tree
Recover Binary Search Tree
-----QUESTION-----
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
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?
-----SOLUTION-----
class Solution { public: void recoverTree(TreeNode *root) { vals.clear(); treeNodes.clear(); inorderTraverse(root); sort(vals.begin(), vals.end()); for (int i = 0; i < treeNodes.size(); ++i) { treeNodes[i]->val = vals[i]; } } void inorderTraverse(TreeNode* root) { if (!root) return; inorderTraverse(root->left); vals.push_back(root->val); treeNodes.push_back(root); inorderTraverse(root->right); } private: vector<int> vals; vector<TreeNode*> treeNodes; };Better Solution: Constant space
class Solution { public: void recoverTree(TreeNode *root) { TreeNode *n1=NULL; TreeNode *n2=NULL; TreeNode *prev=NULL; findTwoNodes(root,n1,n2,prev); if(n1!=NULL && n2!=NULL) { int tmp=n2->val; n2->val=n1->val; n1->val=tmp; } } void findTwoNodes(TreeNode *root, TreeNode *&n1, TreeNode *&n2, TreeNode *&prev) { if(root==NULL) return; findTwoNodes(root->left,n1,n2,prev); if(prev!=NULL && prev->val > root->val) { n2=root; if(n1==NULL) { n1=prev; } } prev=root; findTwoNodes(root->right,n1,n2,prev); } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。