设为首页 加入收藏

TOP

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

评论

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

·C 内存管理 | 菜鸟教 (2025-12-26 20:20:37)
·如何在 C 语言函数中 (2025-12-26 20:20:34)
·国际音标 [ç] (2025-12-26 20:20:31)
·微服务 Spring Boot (2025-12-26 18:20:10)
·如何调整 Redis 内存 (2025-12-26 18:20:07)