標籤:vector epo 假設 poi value ref 遍曆 pes malloc
題目一:矩陣轉置
給定一個矩陣 A, 返回 A 的轉置矩陣。
矩陣的轉置是指將矩陣的主對角線翻轉,交換矩陣的行索引與列索引。
樣本 1:
輸入:[[1,2,3],[4,5,6],[7,8,9]]輸出:[[1,4,7],[2,5,8],[3,6,9]]
樣本 2:
輸入:[[1,2,3],[4,5,6]]輸出:[[1,4],[2,5],[3,6]]
思路:比較簡單,但要注意對矩陣的初始化,如果不初始化會報錯--》reference binding to null pointer of type ‘struct value_type‘
class Solution {public: vector<vector<int>> transpose(vector<vector<int>>& A) { if(A.size()==0){ return A ; } vector<vector<int>> Ar(A[0].size()); for (int i = 0; i < Ar.size(); i++) Ar[i].resize(A.size()); for (int i = 0; i<A[0].size(); i++) { for (int j = 0; j<A.size(); j++) { Ar[i][j] = A[j][i]; } } return Ar ; }};
題目二:
具有所有最深結點的最小子樹
給定一個根為 root 的二叉樹,每個結點的深度是它到根的最短距離。
如果結點具有最大深度,則該結點是最深的。
返回具有最大深度的結點,以該結點為根的子樹中包含所有最深的結點。
輸入:[3,5,1,6,2,0,8,null,null,7,4]輸出:[2,7,4]解釋:
我們傳回值為 2 的結點,在圖中用黃色標記。在圖中用藍色標記的是樹的最深的結點。輸入 "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" 是對給定的樹的序列化表述。輸出 "[2, 7, 4]" 是對根結點的值為 2 的子樹的序列化表述。輸入和輸出都具有 TreeNode 類型。
思路:這個題要注意的是,不是返回一個最深的節點,而是返回一個包含所有最深的子樹,也就是如果是一顆滿二叉樹,那麼就返回跟節點。然後就只要判斷左右兩個孩子哪個節點更深,就返回哪個,如果一樣深就返回當前根節點
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution { public: TreeNode* find(TreeNode* root){ if(root==NULL){ return NULL ; } int depofL = getLen(root->left) ; int depofR = getLen(root->right) ; if(depofL==depofR){ return root ; } if(depofL>depofR){ return find(root->left) ; }else{ return find(root->right) ; } } int getLen(TreeNode* root){ if(root==NULL){ return 0 ; } return 1+max(getLen(root->left),getLen(root->right)) ; } TreeNode* subtreeWithAllDeepest(TreeNode* root) { TreeNode* ans = find(root) ; return ans ; }};
題目三:重構二叉樹
輸入某二叉樹的前序走訪和中序遍曆的結果,請重建出該二叉樹。假設輸入的前序走訪和中序遍曆的結果中都不含重複的數字。例如輸入前序走訪序列{1,2,4,7,3,5,6,8}和中序遍曆序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
思路:這個題就是對照兩種序列把序列分段然後遞迴,無奈vector版還要記錄每一次遞迴時兩種序列的開始和結束位置,還是字串直接取子串比較方便。vector並不知道怎麼取子集,而且就算取了也很占空間,難受,直接貼一下網上的代碼
struct TreeNode * subTree(vector<int> pre, int preStart, int preEnd, vector<int> in, int inStart, int inEnd) { struct TreeNode * rootTree = (struct TreeNode *) malloc (sizeof(struct TreeNode)); rootTree -> val = pre[preStart]; rootTree -> left = NULL; rootTree -> right = NULL; if (preStart == preEnd && inStart == inEnd && pre[preStart] == in[inStart]) return rootTree; int rootIndex = inStart; while (in[rootIndex] != pre[preStart]) rootIndex ++; int newLength = rootIndex - inStart; if (newLength > 0) rootTree -> left = subTree(pre, preStart + 1, preStart + newLength, in, inStart, rootIndex - 1); if (inEnd - rootIndex > 0) rootTree -> right = subTree(pre, preStart + newLength + 1, preEnd, in, rootIndex + 1, inEnd); return rootTree; } struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) { int preLength = pre.size(); int inLength = pre.size(); if (preLength == 0 || inLength == 0) return NULL; return subTree(pre, 0, preLength - 1, in, 0, inLength - 1); }
c++刷題(15/100)矩陣轉置,最深子樹