首页 > 其他 > 详细

leetcode || 99、Recover Binary Search Tree

时间:2015-04-17 18:13:28      阅读:177      评论:0      收藏:0      [点我收藏+]

problem:

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.

Hide Tags
 Tree Depth-first Search
题意,一颗搜索二叉树,将其中的两个节点交换,找出这个两节点 ,恢复搜索二叉树

thinking:

(1)空间复杂度O(N)的算法最简单:

使用map<int ,TreeNode *>结构可以不破坏原来二叉树的结构

中序遍历二叉树,将数值保存到数组a,同时将每一个数值对应的结点指针保存到map<int ,TreeNode *>,增序排序得到数组b。a与b对比,在a中找到位置不同的元素x、y

在map<int ,TreeNode *>中找到x、y对应的结点指针,交换val值即可

(2)空间复杂度为O(1)的算法:参考http://www.cnblogs.com/remlostime/archive/2012/11/19/2777859.html

code:

class Solution {
public:
    void treeWalk(TreeNode* root, TreeNode*& prv, TreeNode*& first, TreeNode*& second)
    {
      if(root==NULL)
         return;
      treeWalk(root->left,prv,first,second);
      if((prv!=NULL)&&(prv->val>root->val)){
          if(first==NULL)
             first=prv;
           second=root;
      }
      prv=root;
      treeWalk(root->right,prv,first,second);
    }
  
    void recoverTree(TreeNode *root) {
        TreeNode* first=NULL;
        TreeNode* second=NULL;
        TreeNode* prv=NULL;
        treeWalk(root,prv,first,second);
        int tmp=first->val;
        first->val=second->val;
        second->val=tmp;
    }
};


leetcode || 99、Recover Binary Search Tree

原文:http://blog.csdn.net/hustyangju/article/details/45098909

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!