LeetCode(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?
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


分析如下:

我非常喜欢这道题目的转换的思路。

第一个办法是改造in order遍历,这个和 Convert Sorted List to Binary Search Tree 表面上完全不同,实际上核心一致,都是根据需要对树的中序遍历进行修改。对普通的中序遍历递归版进行更改,就可以解决这道题目。这个变换可以无穷多。

第二个办法是 Morris遍历,其实是对树的线索化。让叶节点的右孩子指向它的中序遍历的后继,结束遍历之后恢复叶节点的右孩子为NULL。 第二个办法的实现留在以后来完成。


我的代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 /*
  * 解法1 改造in order遍历 http://yucoding.blogspot.com/2013/03/leetcode-question-75-recover-binary.html
  * 解法2 使用morris遍历 1.http://chuansongme.com/n/100461 2.http://www.cnblogs.com/TenosDoIt/p/3445682.html
  */
class Solution { //解法1
public:
    void recoverTree(TreeNode *root, TreeNode* & pre, TreeNode* & first, TreeNode* & second) {
        if (root == NULL) return;
        recoverTree(root->left, pre, first, second);
        if (pre == NULL) {
            pre = root;
        }else {
            if (pre->val > root->val) {
                if (first == NULL) 
                    first = pre;
                second = root;
            }
            pre = root;
        }
        recoverTree(root->right, pre, first, second);
    }
    
    void recoverTree(TreeNode *root) {
         if (root == NULL) return;
         TreeNode* first = NULL;
         TreeNode* second = NULL;
         TreeNode* pre = NULL;
         recoverTree(root, pre, first, second);
         int tmp = first->val;
         first->val = second->val;
         second->val = tmp;
         return;
    }
};

参考资料:

1 yu's coding garden

2 morris transversal 

3 LeetCode:Recover Binary Search Tree

你可能感兴趣的:(LeetCode,tree)