Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
题意:交换了二叉排序树中的两个节点,要求将其还原,不改变树的结构。思路:中序遍历二叉树,如果pre->val > cur->val,那么将这两个节点存在一个容器里,中序遍历之后,如果容器中有两个元素,说明那两个节点相邻,交换这两个节点;如果容器中有四个元素,则将第一个和第四个交换即可。
/**
* 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 swap(int &a,int &b)
{
int t = a;
a = b;
b = t;
}
TreeNode *pre;
void inorder(TreeNode *cur,vector<TreeNode*> &q)
{
if(!cur) return;
inorder(cur->left,q);
if(pre && pre->val > cur->val){
q.push_back(pre);
q.push_back(cur);
}
pre = cur;
inorder(cur->right,q);
}
void recoverTree(TreeNode* root) {
vector<TreeNode*> q;
pre = NULL;
inorder(root,q);
if(q.size() == 2)
swap(q[0]->val,q[1]->val);
else if(q.size() == 4)
{
swap(q[0]->val,q[3]->val);
}
}
};
/**
* 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 swap(int &a,int &b)
{
int t = a;
a = b;
b = t;
}
TreeNode *pre;
void inorder(TreeNode *cur,vector<TreeNode*> &q)
{
if(!cur) return;
inorder(cur->left,q);
if(pre && pre->val > cur->val){
q.push_back(pre);
q.push_back(cur);
}
pre = cur;
inorder(cur->right,q);
}
void recoverTree(TreeNode* root) {
vector<TreeNode*> q;
pre = NULL;
inorder(root,q);
if(q.size() == 2)
swap(q[0]->val,q[1]->val);
else if(q.size() == 4)
{
swap(q[0]->val,q[3]->val);
}
}
};