leetcode || 99、Recover Binary Search Tree

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,算法,二叉树,DFS,中序遍历)