leetcode99. Recover Binary Search Tree

来源:互联网 发布:陆行鲨机甲风暴java 编辑:程序博客网 时间:2024/06/14 21:47

题目

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?

解法

如果空间o(n)的复杂度,可以利用两个向量,一个存储所有的节点,一个存储所有的值,对bst进行中序遍历,如果bst为正确的,那么得到的节点应该是按照顺序排列,所以我们可以将我们得到的值按照顺序排序,然后依次赋值给节点,得到的即为正确的bst。

代码

/** * 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:    vector<TreeNode*> node;    vector<int> value;    void inorder(TreeNode* r)    {        if(r == NULL)            return;        inorder(r->left);        node.push_back(r);        value.push_back(r->val);        inorder(r->right);    }    void recoverTree(TreeNode* root) {        inorder(root);        sort(value.begin(), value.end());        for(int i = 0; i < value.size(); i ++)        {            node[i]->val = value[i];        }    }};
原创粉丝点击