C# · 12月 20, 2021

剑指offer c++

3.从你头到尾打印链表

/**

* struct ListNode {

* int val;

* struct ListNode *next;

* ListNode(int x) :

* val(x),next(NULL) {

* }

* };

*/

class Solution {

public:

vector printListFromTailToHead(ListNode* head) {

vector v1;

vector v2;

if(!head) return v2;

while(head){

v1.push_back(head->val);

head = head->next;

}

for(vector::iterator iter=v1.end()-1;iter!=v1.begin()-1;iter–){

v2.push_back(*iter);

}

return v2;

}

};

重建二叉树:

/**

* DeFinition for binary tree

* struct TreeNode {

* int val;

* TreeNode *left;

* TreeNode *right;

* TreeNode(int x) : val(x),left(NULL),right(NULL) {}

* };

*/

class Solution {

public:

TreeNode* reConstructBinaryTree(vector pre,vector vin) {

if(pre.size()==0) return NULL;

TreeNode* t=new TreeNode(pre[0]);

int index = -1;

for(int i=0;i<vin.size();i++){

if(vin[i]==pre[0])

index = i;

}

vector v1(pre.begin()+(index?1:0),pre.begin()+(index?index+1:index));

vector v2(vin.begin(),vin.begin()+index);

vector v3(pre.begin()+index+1,pre.end());

vector v4(vin.begin()+index+1,vin.end());

t->left = reConstructBinaryTree(v1,v2);

t->right = reConstructBinaryTree(v3,v4);

return t;

}

};