码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--Recover Binary Search Tree

时间:2015-01-14 09:53:16      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:leetcode   traversal   bst   

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.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution 
{
public:
    void recoverTree(TreeNode *root) 
	{   
		if(root == NULL)
			return;
        vector<TreeNode*> res;
		pre_search(root,res);
		if(res.size() == 1)
			return;
		bool flag = false;
		vector<int> temp;
		for(int i=1; i<res.size(); i++)
		{
			if(res[i]->val <= res[i-1]->val)
			{
				if(flag == false)
				{
					temp.push_back(i-1);
					flag = true;
				}
				else
				{
					temp.push_back(i);
					flag = false;
				}
			}
		}
		int n = temp.size();
		if(n == 1)
		{
			int pre = temp[0];
			int t = res[pre]->val;
			res[pre]->val = res[pre+1]->val;
			res[pre+1]->val = t;
		}
		else
		{
			int pre = temp[0];
			int end = temp[1];
			int t = res[pre]->val;
			res[pre]->val = res[end]->val;
			res[end]->val = t;
		}
		return ;
    }
	void pre_search(TreeNode* root, vector<TreeNode*>& res)
	{
		if(root == NULL)
			return;
		pre_search(root->left,res);
		res.push_back(root);
		pre_search(root->right,res);
	}	
};


LeetCode--Recover Binary Search Tree

标签:leetcode   traversal   bst   

原文地址:http://blog.csdn.net/shaya118/article/details/42695763

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!