中序遍历的话BST应该递增,那么在中序遍历过程中检查是否有节点违反这一规则即可。
-
/**
-
* Definition for binary tree
-
* struct TreeNode {
-
* int val;
-
* TreeNode *left;
-
* TreeNode *right;
-
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
-
* };
-
*/
-
class Solution {
-
public:
-
void errNodes(TreeNode *node, TreeNode *&prev, TreeNode **nodes) {
-
if(NULL==node) return;
-
errNodes(node->left, prev, nodes);
-
if(prev&&prev->val>node->val)
-
{
-
nodes[1]=node;
-
if(!nodes[0]) nodes[0]=prev;
-
}
-
prev=node;
-
errNodes(node->right,prev,nodes);
-
}
-
void recoverTree(TreeNode *root) {
-
if(NULL==root) return;
-
TreeNode *nodes[2]={0};
-
TreeNode *prev=NULL;
-
errNodes(root,prev,nodes);
-
if(nodes[0]&&nodes[1])
-
swap(nodes[0]->val,nodes[1]->val);
-
}
-
};
阅读(489) | 评论(0) | 转发(0) |