日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

剑指offer 算法(链表 树)

發布時間:2025/10/17 编程问答 7 豆豆
生活随笔 收集整理的這篇文章主要介紹了 剑指offer 算法(链表 树) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述

輸入一個鏈表,從尾到頭打印鏈表每個節點的值。

解析:逆轉鏈表,與棧順序一致,可以用輔助棧解決這個問題。

/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */ class Solution { public:vector<int> printListFromTailToHead(struct ListNode* head) {vector<int> stack;vector<int> result;while(head){stack.push_back(head->val);head = head->next;}while(!stack.empty()){int val = stack.back();result.push_back(val);stack.pop_back();}return result;} };
題目描述

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹并返回。

/*** Definition for binary tree* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/ class Solution { public: struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {int size = pre.size();if(size == 0){return NULL;}return PreInBuildTree(pre,in,0,0,size);} private:TreeNode* PreInBuildTree(vector<int> pre,vector<int> in,int preIndex,int inIndex,int size){if(size == 0){return NULL;}// 根節點TreeNode* root = new TreeNode(pre[preIndex]);// 尋找根節點在中序遍歷數組的下標int index = 0;for(int i = 0;i < size;++i){// 注意:inorder[inIndex+i]if(pre[preIndex] == in[inIndex+i]){index = inIndex+i;break;}}// 左子樹個數int leftSize = index - inIndex;// 右子樹個數int rightSize = size - leftSize - 1;// 左子樹root->left = PreInBuildTree(pre,in,preIndex+1,inIndex,leftSize);// 右子樹root->right = PreInBuildTree(pre,in,preIndex+1+leftSize,index+1,rightSize);return root;} };

總結

以上是生活随笔為你收集整理的剑指offer 算法(链表 树)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。