设为首页 加入收藏

TOP

LeetCode--Recover Binary Search Tree
2015-07-20 17:24:35 来源: 作者: 【 】 浏览:1
Tags:LeetCode--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.

/**
 * 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
  
    res;
		pre_search(root,res);
		if(res.size() == 1)
			return;
		bool flag = false;
		vector
   
     temp; for(int i=1; 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
     
      & res) { if(root == NULL) return; pre_search(root->left,res); res.push_back(root); pre_search(root->right,res); } };
     
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇[LeetCode]Divide Two Integers 下一篇Canvas图保存成图片或pdf

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·求navicat for mysql (2025-12-26 13:21:33)
·有哪位大哥推荐一下m (2025-12-26 13:21:30)
·MySQL下载与安装教程 (2025-12-26 13:21:26)
·Linux_百度百科 (2025-12-26 12:51:52)
·Shell 流程控制 | 菜 (2025-12-26 12:51:49)