3.从你头到尾打印链表
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> v1;
vector<int> v2;
if(!head) return v2;
while(head){
v1.push_back(head->val);
head = head->next;
}
for(vector<int>::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<int> pre,vector<int> 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<int> v1(pre.begin()+(index?1:0),pre.begin()+(index?index+1:index));
vector<int> v2(vin.begin(),vin.begin()+index);
vector<int> v3(pre.begin()+index+1,pre.end());
vector<int> v4(vin.begin()+index+1,vin.end());
t->left = reConstructBinaryTree(v1,v2);
t->right = reConstructBinaryTree(v3,v4);
return t;
}
};