【計劃執行報告】Day9 04-08 在校慶124週年被二叉樹暴虐
Day9 04-08 在校慶124週年被二叉樹暴虐
今天是:
- 計劃執行的第9天
- 124週年校慶
- 機器學習結課的一天
1.今日動態
- 校慶日&機器學習結課之日我的相關書籍也到來了,我發誓這是最後一波淘書了!!!
2.計劃執行報告
2.1近期計劃(03-31-04-12)
- 《機器學習中的數學》前三章(線性代數相關)
2.完成專業課的作業(流體機械能轉化、生物質能,新能源熱利用可以往後稍稍);
3.備戰藍橋杯,爲此:①利用中午1h左右的時間補充數據結構知識(優先Leetcode“探索”模塊);②C/C++語法知識;③常見數據結構的構造與基本操作實現;④必要的練習與練題總結(比如時長1:30虛擬競賽與“覆盤”)
2.2今日計劃表
2.3實際時間分配
- 二叉樹僅僅做出了3題,耗時太久(上午2小時一道題沒弄出來,我太菜了);
- 中午、下午接連領了波快遞,把節奏搞亂了;
- 從時間分配也能看出來,近兩天的學習熱情有點被消磨掉了,需要好好調整下。
3.關於我校慶日被二叉樹虐這檔事
昨天多快樂今天就多自閉。上午兩小時原計劃完成4題,結果整天下來就做出了3題,我覺得還是得調整下思路,有些東西不能強求全部自己想,想個20min沒構思出來的話就看看提示吧。總之,時間寶貴,不能頭鐵!
下面我僅把做過的題目以及我的通過的解答列出來,等系統學完後再抽時間單獨總結,畢竟現在自己尚未進入Leetcode的“偉大航路”。
習題1
根據後序遍歷數組確定根節點,然後在中序遍歷數組中找到根節點的位置,其前後就分別對應左子樹和右子樹,然後依次遞歸下去。
class Solution {
public:
int find(vector<int> v,int s,int t,int key){
for(int i=s;i<=t;i++)
if(v[i]==key)
return i;
return -1;
}
TreeNode* buildSubTree(vector<int> inorder,
vector<int> postorder,int inS,int inT,int postT){
if(inS>inT){//子樹爲空
return NULL;
}
int rootval=postorder[postT];//根節點值
TreeNode* root=new TreeNode(rootval);//創建樹
root->left=NULL;
root->right=NULL;
//獲取根節點在中序序列的下標
int root_pos=find(inorder,inS,inT,rootval);
int left_end=postT-(inT-root_pos)-1;
int right_end=postT-1;//右子樹根節點位置
root->left=buildSubTree(inorder,postorder,inS,
root_pos-1,left_end);
root->right=buildSubTree(inorder,postorder,
root_pos+1,inT,right_end);
return root;
}
TreeNode* buildTree(vector<int>& inorder,
vector<int>& postorder) {
return buildSubTree(inorder,postorder,0,
inorder.size()-1,postorder.size()-1);
}
}
習題2
思路與上題差不多。
class Solution {
public:
int find(vector<int> v,int s,int t,int key){
for(int i=s;i<=t;i++)
if(key==v[i])
return i;
return -1;
}
TreeNode* buildSubTree(vector<int> preorder,
vector<int> inorder,int preS,int inS,int inT) {
if(inS>inT)
return NULL;
int root_val=preorder[preS];
TreeNode* root=new TreeNode(root_val);
int root_pos=find(inorder,inS,inT,root_val);
root->left=buildSubTree(preorder,inorder,
preS+1,inS,root_pos-1);
root->right=buildSubTree(preorder,inorder,
preS+root_pos-inS+1,root_pos+1,inT);
return root;
}
TreeNode* buildTree(vector<int>& preorder,
vector<int>& inorder) {
return buildSubTree(preorder,inorder,
0,0,inorder.size()-1);
}
};
注意,要還原一個二叉樹,所給的兩種遍歷序列中一定要有中序遍歷。
習題3
這個是滿二叉樹,所以實現起來不難。
class Solution {
public:
void sub_connect(Node* nl,Node* nr) {
if(!nl)
return;
if(nr){//根節點連接
nl->next=nr;
sub_connect(nr->left,nr->right);
sub_connect(nl->right,nr->left);
}
sub_connect(nl->left,nl->right);
}
Node* connect(Node* root) {
sub_connect(root,NULL);
return root;
}
};