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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值