Vic
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # LeetCode | Data Structure I | 14 Days Challenge | Day 11-12 ###### tags: `LeetCode` `Data Structure I` `14 Days Challenge` ## Day 11 ### [[104. Maximum Depth of Binary Tree](104. Maximum Depth of Binary Tree)](https://leetcode.com/problems/maximum-depth-of-binary-tree/?envType=study-plan&id=data-structure-i) ### 題目敘述 >*Given the root of a binary tree, return its maximum depth.* >*A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.* ### 測資 Example 1: ![](https://i.imgur.com/SbGp45O.png) :::info Input: root = [3,9,20,null,null,15,7] Output: 3 ::: Example 2: :::info Input: root = [1,null,2] Output: 2 ::: ### 數值範圍 The number of nodes in the tree is in the range [0, 104]. -100 <= Node.val <= 100 ### 核心概念 ==tree、DFS、Recursion== ### 想法 又來到我最喜歡的tree環節! 本題仍然是搭配dfs,遞迴找出最高高度,並隨時記錄最大值。 ***time : 5-10 mins time complexity : $O(n)$ space complexity : $O(n)$*** ### 程式碼 ```c++=1 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int maxx = 0; void dfs(TreeNode* root, int level){ maxx = max(maxx, level); if(root->left != nullptr) dfs(root->left, level + 1); if(root->right != nullptr) dfs(root->right, level + 1); } int maxDepth(TreeNode* root) { if(root == nullptr) return maxx; dfs(root, maxx + 1); return maxx; } }; ``` ### [102. Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/?envType=study-plan&id=data-structure-i) ### 題目敘述 >*Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).* ### 測資 Example 1: ![](https://i.imgur.com/KX71HUy.png) :::info Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]] ::: Example 2: :::info Input: root = [1] Output: [[1]] ::: Example 3: :::info Input: root = [] Output: [] ::: ### 數值範圍 The number of nodes in the tree is in the range [0, 2000]. -1000 <= Node.val <= 1000 ### 核心概念 ==tree、Levelorder Traversal、BFS== ### 想法 上次介紹了三種樹的搜尋方式,現在則介紹第四種! * Levelorder 一層一層,且由左至右輸出,核心概念為BFS搭配queue實作。 利用queue特性,將node的left child 、right child 加入至queue中(queue資料型態為structure TreeNode*),當queue為空,則代表已完成搜尋。 留言區有很多大佬,寫法不只一種,這是我自己的想法~ ***time : 10~15 mins time complexity : $O(n)$ space complexity : $O(n)$*** ### 程式碼 ```c++=1 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { if(root == nullptr) return {}; vector<vector<int>> ans; vector<int> v; queue<TreeNode*> q; TreeNode* node; q.push(root); while (!q.empty()) { int n = q.size(); while(n--){ node = q.front(); v.push_back(node->val); q.pop(); if(node->left != nullptr) q.push(node->left); if(node->right != nullptr) q.push(node->right); } ans.push_back(v); v.clear(); } return ans; } }; ``` ### [101. Symmetric Tree](https://leetcode.com/problems/symmetric-tree/?envType=study-plan&id=data-structure-i) ### 題目敘述 >*Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).* ### 測資 Example 1: ![](https://i.imgur.com/R77V1nb.png) :::info Input: root = [1,2,2,3,4,4,3] Output: true ::: Example 2: ![](https://i.imgur.com/robkIou.png) :::info Input: root = [1,2,2,null,3,null,3] Output: false ::: ### 核心概念 ==tree、Traversal、Recursion== ### 數值範圍 The number of nodes in the tree is in the range [1, 1000]. -100 <= Node.val <= 100 ### 想法 本題為檢查tree是否為鏡像。 **left->left要等於right->right left->right要等於right->left** 將遞迴限制、條件規劃好,便輕鬆完工~遞迴的難處便在如何**設置條件、限制**,多練習,熟能生巧! ***time : 25-30 mins time complexity : $O(n)$ space complexity : $O(1)$*** ### 程式碼 ```c++=1 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool status = true; void CheckMirror(TreeNode* left, TreeNode* right){ if(!status) return; if(left == nullptr && right == nullptr) return; if(left == nullptr || right == nullptr) {status = false; return;} if(left->val != right->val) {status = false; return;} CheckMirror(left->left, right->right); CheckMirror(left->right, right->left); } bool isSymmetric(TreeNode* root) { if(root == nullptr) return true; CheckMirror(root->left, root->right); return status; } }; ``` ## Day 10 ### [112. Path Sum](https://leetcode.com/problems/path-sum/?envType=study-plan&id=data-structure-i) ### 題目敘述 >*Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.* >*A **leaf** is a node with no children.* ### 測資 Example 1: ![](https://i.imgur.com/grsHv8q.png) :::info Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: The root-to-leaf path with the target sum is shown. ::: Example 2: ![](https://i.imgur.com/RlFrq15.png) :::info Input: root = [1,2,3], targetSum = 5 Output: false Explanation: There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5. ::: Example 3: :::info Input: root = [], targetSum = 0 Output: false Explanation: Since the tree is empty, there are no root-to-leaf paths. ::: ### 核心概念 ==tree、DFS、Recursion== ### 數值範圍 The number of nodes in the tree is in the range [0, 5000]. -1000 <= Node.val <= 1000 -1000 <= targetSum <= 1000 ### 想法 本題需要輸出root-to-leaf(從根到葉)的數值總和是否等於target。 當提到總和,**不一定要用加的**,可以換個方式思考,可以利用總和 - 該節點的值,並傳回副函式,當遞迴做至leaf時(have no child),判斷條件,傳回布林值。 ***time : 25~30 mins time complexity : $O(n)$ space complexity : $O(1)$*** ### 程式碼 ```c++=1 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int sum = 0; bool hasPathSum(TreeNode* root, int targetSum) { if(root == nullptr) return false; if(targetSum == root->val && root->left == nullptr && root->right == nullptr) return true; return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val); } }; ``` ### [226. Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/?envType=study-plan&id=data-structure-i) ### 題目敘述 >*Given the root of a binary tree, invert the tree, and return its root.* ### 測資 Example 1: ![](https://i.imgur.com/XkoKXCG.png) :::info Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1] ::: Example 2: ![](https://i.imgur.com/gLTDEWx.png) :::info Input: root = [2,1,3] Output: [2,3,1] ::: Example 3: :::info Input: root = [] Output: [] ::: ### 核心概念 ==tree、Recursion== ### 數值範圍 The number of nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100 ### 想法 本題需要將樹**左右顛倒**。 要記得Swap是將**整個節點的位址、值皆交換,因此node的child也會跟著交換**。 ***time : 10~15 mins time complexity : $O(n)$ space complexity : $O(1)$*** ### 程式碼 ```c++=1 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* invertTree(TreeNode* root) { if(root == nullptr) return root; swap(root->left, root->right); invertTree(root->left); invertTree(root->right); return root; } }; ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    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

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully