zoukankan      html  css  js  c++  java
  • Leetcode: Recover Binary Search Tree

    题目

    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?

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

     

    思路:

    1. A solution using O(n) space is pretty straight forward, 指的是中序遍历

    2. 依然使用中序遍历, 但只需要维持大小为 2 的窗口即可

    3. 具体来讲, 因为 BST 的中序遍历是一个递增的数组, 我们可以通过分析递增数组交换两个元素后的情况来进行编码, 当数组中连续的两个数交换时, 只会出现一次逆序, 否则, 必然恰好两次逆序, 所以, 我们设置一个 candidate[2] 来存储第一次逆序的两个节点. 假如发现了第二次逆序, 那么直接找到了, 若没发现第二次逆序, 那么必然是连续的两个数交换, candidate 中存储的两个节点就是答案

    代码:

    class Solution {
    public:
    	TreeNode* candidate[2];
    	TreeNode* pre;
    	bool findone;
    	bool ans;
        void recoverTree(TreeNode *root) {
    		if(root == NULL)
    			return;
    
    		ans = false;
    		findone = false;
    
    		pre = NULL;
    		inorder(root);
    		if(ans)
    			return;
    		else{
    			int tmp = candidate[0]->val;
    			candidate[0]->val = candidate[1]->val;
    			candidate[1]->val = tmp;
    		}
    		// just for fun
    		return;
        }
    
    	void inorder(TreeNode *root) {
    		if(root == NULL)
    			return;
    
    		if(root->left != NULL && !ans) 
    			inorder(root->left);
    		
    		if(pre == NULL)
    			pre = root;
    		if(root->val < pre->val ) {	// findone
    			if(findone) {	// 找到另一个
    				int tmp = candidate[0]->val;
    				candidate[0]->val = root->val;
    				root->val = tmp;
    				ans = true;
    				
    			}else{
    				candidate[0] = pre;
    				candidate[1] = root;
    				findone = true;
    			}
    		}
    		pre = root;
    		if(root->right &&!ans)
    			inorder(root->right);
    	}
    };
    

      

  • 相关阅读:
    C#泛型
    Chrome 中调试Javascript
    Oracle分页查询语句
    WordCount2.2
    第一周博客作业
    WordCount--统计输入文件的字符数、行数、单词数(java)--初级功能
    PHP数据库操作
    PHP安全函数
    PHP基础
    用户/目录操作
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3468310.html
Copyright © 2011-2022 走看看