99. 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?

1.別人的解答思路

這裏是用中序遍歷進行的,中序遍歷的模板如下;

private void traverse (TreeNode root) {
   if (root == null)
      return;
   traverse(root.left);
   // Do some business
   traverse(root.right);
}

因此,用兩個全局變量來定義,找到這兩個變量。第一個變量選擇前者大於後者的前者,第二個變量選擇前者大於後者的後者

在上述代碼中,在do some business 裏插入代碼

How do we find these two elements? For example, we have the following tree that is printed as in order traversal:

6, 3, 4, 5, 2

We compare each node with its next one and we can find out that 6 is the first element to swap because 6 > 3 and 2 is the second element to swap because 2 < 5.

Really, what we are comparing is the current node and its previous node in the "in order traversal".

Let us define three variables, firstElement, secondElement, and prevElement. Now we just need to build the "do some business" logic as finding the two elements. See the code below:


/**
 * 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:
    TreeNode* pre = new TreeNode(INT_MIN);
    TreeNode* first = NULL;
    TreeNode* second = NULL;
    
    void recover(TreeNode* root){
        if(root == NULL) return;
        recover(root->left);
        
        if(first == NULL && pre->val >= root->val)
            first = pre;
        if(first != NULL && pre->val >= root->val)
            second = root;
        pre = root;
        
        recover(root->right);
    }
    
    void recoverTree(TreeNode* root) {
        recover(root);
        int temp = first->val;
        first->val = second->val;
        second->val = temp;
    }
};


發佈了171 篇原創文章 · 獲贊 7 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章