# 演算法作業 HW9 # 觀念題 ## 第一題  ## 第二題  ## 第三題  # 程式題 ## 第四題 ### 通過畫面截圖  ### 程式碼 ```C++= /** * 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* invertTree(TreeNode* root) { if (!root) return root; TreeNode *left = root->left; root->left = invertTree(root->right); root->right = invertTree(left); return root; } }; ``` ### 解題思路 遍歷每個節點,交換其左右子節點,然後對左右子節點進行相同操作。 ### 花費時間 20分鐘 ### 自己完成的比例 全部自己完成 ## 第五題 ### 通過畫面截圖  ### 程式碼 ```C++= /** * 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 { private: int count = 0; public: int kthSmallest(TreeNode* root, int k) { if (!root) return -1; int leftVal = kthSmallest(root->left, k); if (leftVal != -1) return leftVal; count++; if (count == k) return root->val; return kthSmallest(root->right, k); } }; ``` ### 解題思路 因為是二叉搜索樹,inorder可以得到一個從小到大排列的list,因此用inorder來解決這道題目。 由於需要返回第k小的元素,需要記錄已經訪問過的元素個數count,當count等於k時,返回當前節點的值。 ### 花費時間 半小時 ### 自己完成的比例 全部由自己完成 # 心得 這次的影片部分還是跟上次一樣多,但是難度相較於上次有所減少,聽了一次基本都能理解。 然後作業部份也變少了,成試題稍微動點腦筋都能解題。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up