剑指offer 算法(链表 树)
生活随笔
收集整理的這篇文章主要介紹了
剑指offer 算法(链表 树)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數字。例如輸入前序遍歷序列{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;} };
輸入一個鏈表,從尾到頭打印鏈表每個節點的值。
解析:逆轉鏈表,與棧順序一致,可以用輔助棧解決這個問題。
/** * 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 算法(链表 树)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指offer 算法(数组 字符串)
- 下一篇: 剑指offer 算法(栈和队列 查找和