99 recovery binary serach tree

1 2 3 4 5 6

1 5 3 4 2 6

5>3 发现第一个错误节点5,prev

4>2 发现第二个错误节点2 ,curr


void inOrder(struct TreeNode * root,struct TreeNode** prev,struct TreeNode** first,struct TreeNode** second){
    
    


    if(root == NULL) return;
    //search left tree
    inOrder(root->left, prev, first, second);
    
    //in inorder traversal of BST, prev should always have smaller value than current value
    
    if((*prev) != NULL && (*prev)->val >= root->val){
      
        //incorrect smaller node is always found as prev node
        if(*first == NULL) 
            *first = *prev;
      //incorrect larger node is always found as curr(root) node
        *second = root;
    }
    
    
    //update prev node
    *prev = root;

    //search right tree
    inOrder(root->right, prev, first, second);
}

void recoverTree(struct TreeNode* root) {
    //use inorder traversal to detect incorrect node
    
    struct TreeNode * prev = NULL;
    struct TreeNode * first = NULL;
    struct TreeNode * second = NULL;
    
    inOrder(root, &prev, &first, &second);
    

    int temp = first->val;
    first->val = second->val;
    second->val = temp;
}       
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容