首页 > 代码库 > LeetCode "Recover Binary Search Tree"
LeetCode "Recover Binary Search Tree"
An example of in-order traversal application. My intuition is that, we have to serialize it into an array and check, but in-order traversal does exactly the same thing. Then, you only need bookmark some runtime records to get it accepted :)
class Solution {public: vector<TreeNode *> rec; queue<TreeNode *> q; void go(TreeNode *root) { if(root->left) go(root->left); // update record if(q.size() == 2) q.pop(); q.push(root); // check if(q.size() > 1) { int v1 = q.back()->val; int v0 = q.front()->val; if(v0 > v1) { if(rec.empty()) { rec.push_back(q.front()); rec.push_back(q.back()); } else { rec[1] = q.back(); } } } if(root->right) go(root->right); } void recoverTree(TreeNode *root) { if (!root) return; if(!root->left && !root->right) return; go(root); int tmp = rec[0]->val; rec[0]->val = rec[1]->val; rec[1]->val = tmp; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。