加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

剑指offer c++

发布时间:2020-12-15 04:49:49 所属栏目:百科 来源:网络整理
导读: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

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

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;

}

};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读