5.1.5 Recover Binary Sear Tree

来源:互联网 发布:云计算是什么 编辑:程序博客网 时间:2024/06/18 11:35
Notes: 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?  Solution: 1. recursive solution. O(n) space. get inorder list first. 2. recursive solution. O(n) space. with only auxiliary two pointers. 3. Morris inorder traversal. O(1) space. with only auxiliary two pointers. */

解题思路:先对树进行中序遍历,将遍历的结果放在容器中,然后 找到两个乱序的数。

struct TreeNode {    int val;    TreeNode *left;    TreeNode *right;    TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:    // first solution    void recoverTree_1(TreeNode *root) {        vector<TreeNode *> inorder;        inorderTraversal(root, inorder);        TreeNode *first = NULL, *second = NULL;        for (int i = 1; i < inorder.size(); ++i)        {            if (inorder[i-1]->val < inorder[i]->val)                continue;            if (!first)                first = inorder[i-1];            second = inorder[i];        }        swap(first->val, second->val);    }    void inorderTraversal(TreeNode *root, vector<TreeNode *> &inorder) {        if (!root) return;        inorderTraversal(root->left, inorder);        inorder.push_back(root);        inorderTraversal(root->right, inorder);    }
};


0 0
原创粉丝点击