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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章