leetcode || 99、Recover Binary Search Tree

本文详细介绍了如何在不改变原有结构的情况下,通过中序遍历和数组辅助,找到并修复搜索二叉树中由于误操作导致的两个节点交换问题。提供了空间复杂度为O(1)的高效解决方案。

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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值