leetcode第六题 recovertree 递归中序

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2

Example 2:

Input: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3

Follow up:

  • A solution using O(n) space is pretty straight forward.
  • Could you devise a constant space solution?

说实话,一开始题目没看懂,实际上是将二叉树恢复成按照中序排列的样子,下面这个算法写的比较通俗易懂,但是复杂度的O(1)的,主要思路利用了二叉树的中序遍历。

//
// Created by jun on 19-3-18.
//
#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>

using namespace std;
//////链表的节点创建,创建一个节点/////////
struct TreeNode {
    int val;
    TreeNode *lp;
    TreeNode *rp;
    TreeNode();
    TreeNode(int a){val=a;lp=NULL;rp=NULL;};   ////这里创建一个结构体的构造函数,很方便,初始化的时候直接进行初始化
};


////中序遍历递归写法

void BiMid(TreeNode *root)
{
    if(!root)
        return;
    BiMid(root->lp);
    cout <<root->val <<endl;
    BiMid(root->rp);
}

/////中序遍历,把节点指针和对应的数值都记录下来
void record_pv(TreeNode *root, vector <TreeNode *> &list,vector <int> &val)
{
    if(!root)
        return;
    record_pv(root->lp,list,val);
    list.push_back(root);
    val.push_back(root->val);
    record_pv(root->rp,list,val);
}

///////排序,然后重新赋值

void recover(TreeNode *root,vector <TreeNode *> &list,vector <int> &val)
{
    if(!root)
        return;
    record_pv(root,list,val);
    sort(val.begin(),val.end());
    size_t i =0;
    for(auto a : list)
    {
        a->val = val[i];
        i++;
    }

}


int main()
{
    TreeNode *a = new TreeNode(1);
    TreeNode *b = new TreeNode(2);
    TreeNode *c = new TreeNode(3);
    TreeNode *d = new TreeNode(4);
    TreeNode *e = new TreeNode(5);
    TreeNode *f = new TreeNode(6);

    a->lp = b;
    a->rp = c;
    b->lp = d;
    b->rp = e;
    c->lp = f;


    BiMid(a);
    vector <TreeNode *> l;
    vector <int> v;
    recover(a,l,v);
    BiMid(a);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_31638535/article/details/88640186