K-DA
    • 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
    • Make a copy
    • 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 Make a copy 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
    [toc] ## Các khái niệm, tính chất - Cây (tree) là một đồ thị vô hướng liên thông không có chu trình. - Tập hợp các cây không có đỉnh chung gọi là một rừng (forest). ![](https://hackmd.io/_uploads/ByZVuYTPh.png) - Các khái niệm: bậc của nút, bậc của cây, nút cha, nút con, nút gốc, nhánh, lá, mức của nút, độ dài đường đi từ gốc đến nút x, tổng độ dài, độ dài trung bình, độ cao của cây... ## 1. Cây nhị phân (Binary tree) - **Khái niệm:** Cây nhị phân là cây mà mỗi nút có tối đa 2 cây con. - **Một số tính chất:** + Số nút nằm ở mức $i \le 2^i$. + Số nút lá $\le 2^{h-1}$, với $h$ là chiều cao của cây. + Chiều cao của cây $h \ge \log_2(N)$, với $N$ là số nút trong cây). + Số nút trong cây $\le 2^{h-1}$. - **Các loại cây nhị phân:** cây nhị phân hoàn chỉnh, cây nhị phân đầy đủ (hoàn chỉnh + các nút lá có cùng mức), cây nhị phân cân bằng... ![](https://hackmd.io/_uploads/HyQM0r7u2.png) ![](https://hackmd.io/_uploads/SJ8q3HXdh.png =300x200) - **Biểu diễn cây nhị phân:** ```cpp= struct Node{ int data; Node* left; Node* right; }; ``` - **Duyệt cây nhị phân:** **- Theo chiều rộng:** Là cách thăm các nút bắt đầu từ bậc thấp (hoặc cao nhất) và di chuyển xuống dưới (hoặc lên trên) theo bậc. Ở mỗi bậc thăm nút từ trái sang phải (hoặc từ phải sang trái). - Thứ tự theo hình trên: $1$ $2$ $3$ $4$ $5$ $6$ $7$. ```cpp= void printLevelOrder(Node* root){ if (root == NULL) return; queue <Node*> q; while(q.size() > 0){ Node* tmp = q.front(); // lấy phần tử đầu tiên q.pop(); // xóa khỏi hàng đợi cout<<tmp->data<<" "; // thêm các nút con if (tmp->left != NULL) q.push(tmp->left); if (tmp->right != NULL) q.push(tmp->right); } } ``` **- Theo chiều sâu:** có 3 cách cơ bản a. Duyệt tiền thứ tự: gốc - trái - phải - Thứ tự theo hình trên: $1$ $2$ $4$ $5$ $3$ $6$ $7$. ```cpp= void NLR(Node* root){ // Node - Left - Right if (root != NULL){ cout<<root->data<<" "; NLR(root->left); NLR(root->right); } } ``` b. Duyệt trung thứ tự: trái - gốc - phải - Thứ tự theo hình trên: $4$ $2$ $5$ $1$ $6$ $3$ $7$. ```cpp= void LNR(Node* root){ // Left - Node - Right if (root != NULL){ LNR(root->left); cout<<root->data<<" "; LNR(root->right); } } ``` c. Duyệt hậu thứ tự: trái - phải - gốc - Thứ tự theo hình trên: $4$ $5$ $2$ $6$ $7$ $3$ $1$ ```cpp= void LRN(Node* root){ // Left - Right - Node if (root != NULL){ LRN(root->left); LRN(root->right); cout<<root->data<<" "; } } ``` ## 2. Cây nhị phân tìm kiếm (Binary search tree - BST) ### Khái niệm: - Là cây nhị phân trong đó tại mỗi nút, khóa của nút đang xét lớn hơn khóa của tất cả các nút thuộc cây con trái và nhỏ hơn khóa của tất cả các nút thuộc cây con phải. Ví dụ: ![](https://hackmd.io/_uploads/B1_Yw1Rwh.png) ### Các thao tác: #### Tìm kiếm một phần tử ```cpp= Node* searchNode(Node* root, int key){ if (root == NULL) return root; else if (root->data == key) return root; else if (root->data < key) return searchNode(root->right, key); else return searchNode(root->left, key); } ``` #### Thêm một phần tử ```cpp= void insertNode(Node* root, int key){ Node* tmp = searchNode(root, key); if (tmp == NULL){ tmp = new Node; tmp->data = key; tmp->left = tmp->right = NULL; } } ``` #### Xóa một phần tử ```cpp= void replaceNode(Node* &p, Node* &t){ if(t->left != NULL){ replaceNode(p,t->right); // tìm nút trái nhất cây con phải } else{ p->data = t->data; p = t; t = t->right; } } void deleteNode(Node* root, int key){ // xóa phần tử khóa key Node* tmp = searchNode(root, key); // tìm nút có khóa là key if (tmp == NULL) return root; // dừng nếu không tồn tại nút có khóa key Node* p = tmp; if (tmp->left == NULL){ // không có con trái, chỉ có thể có 1 con phải hoặc không tmp = tmp->right; } else if (t->right == NULL){ // không có con phải, chỉ có thể có 1 con trái hoặc không tmp = tmp->left; } else { // nút có đủ 2 con replaceNode(p,tmp->right); // trường hợp tìm nút trái nhất của cây con phải } delete p; //p bây giờ lưu địa chỉ của nút thay thế - không còn cần sử dụng nữa } ``` #### Hủy toàn bộ cây: duyệt LRN ### Nhận xét: - Tất cả các thao tác đều có độ phức tạp trung bình là $O(h)$, với $h$ là chiều cao của cây. - Trong trường hợp tốt nhất $h=\log_2(n)$. - Trong trường hợp xấu nhất, cây bị suy biến (đường thẳng), khi đó $h=n$. => Vì vậy cần cải tiến cấu trúc của BST để đạt được chi phí có các thao tác là $\log_2(n)$. ## Cây AVL (Cây nhị phân cân bằng) - Mô tả: - Là cây tìm kiếm nhị phân (BST) tự cân bằng. - Tại mọi nút, chiều cao của hai cây con chênh lệch không quá 1. - Khi tính cân bằng AVL tại một nút bị phá vỡ, cần một hoặc hai phép quay để tái cân bằng AVL cây tại nút đó và biến đổi cây trở thành cân bằng AVL. - Xây dựng cây AVL ```cpp= struct Node{ int data; Node* left; Node* right; int height; } ``` - Chiều cao của một Node chính là số các node trên một đường dẫn dài nhất từ Node đó đến Node = NULL. Và quy ước Node = NULL có chiều cao bằng 0. ```cpp= int getHeight(Node* root){// lấy chiều cao của một nút if (root==NULL) return 0; return root->height; } ``` - Đối với một cây cân bằng, chỉ số cân bằng (CSCB) của mỗi nút chỉ có thể mang một trong ba giá trị sau đây: $CSCB(p)=0$ ⇔ Độ cao cây trái $(p)$ = Độ cao cây phải $(p)$ $CSCB(p)=1$ ⇔ Độ cao cây trái $(p)$ > Độ cao cây phải $(p)$ $CSCB(p)=-1$ ⇔ Độ cao cây trái $(p)$ < Độ cao cây phải $(p)$ * Các kĩ thuật quay cây AVL Có thể thấy cây BST khi không cân bằng sẽ bị lệch sang phía bên trái hoặc bên phải. Để điều chỉnh lại ta cần phải quay cây sang phía ngược lại. - Quay trái: áp dụng khi cây bị lệch phải ![](https://hackmd.io/_uploads/rykzw3APh.png) - Quay phải: áp dụng khi cây bị lệch trái ![](https://hackmd.io/_uploads/rJ9Nv2RP3.png) ```cpp= Node* rightRotate(Node* root){ Node* x=root->left; //Quay phai root->left=x->right; x->right=root; //Cap nhat chieu cao root->height=1+ max(getHeight(root->right), getHeight(root->left)); x->height=1+ max(getHeight(x->right), getHeight(x->left)); //Tra ve nut goc hien tai return x; } Node* leftRotate(Node* root){ Node* y=root->right; //Quay trai root->right=y->left; y->left=root; //Cap nhat chieu cao root->height=1+ max(getHeight(root->right), getHeight(root->left)); y->height=1+ max(getHeight(y->right), getHeight(y->left)); //Tra ve nut goc hien tai return y; } ``` ### Các trường hợp cây bị lệch a. Trái trái ![](https://hackmd.io/_uploads/BkOQC2CD3.png) - Xảy ra khi: $height(X)$ – $height(Y)$ > $1$ và $value(Đỏ)$ < $value(X)$ - Xử lý: quay phải Node root `rotateRight(root)` b. Phải phải ![](https://hackmd.io/_uploads/r1w302Cv3.png) - Xảy ra khi: $height(X)$ – $height(Y)$ < $-1$ và value(Đỏ) > value(Y) - Xử lý: quay trái Node $root$ `rotateLeft(root)` c. Trái phải ![](https://hackmd.io/_uploads/Bklbkp0P2.png) - Xảy ra khi: $height(X)$ – $height(Y)$ < $1$ và $value(Đỏ)$ > $value(X)$ - Xử lý: `rotateLeft(X)` $\rightarrow$`rotateRight(root)` d. Phải trái ![](https://hackmd.io/_uploads/H1gVkpRP2.png) - Xảy ra khi: $height(X)$ – $height(Y)$ < $-1$ và $value(Đỏ)$ < $value(Y)$ - Xử lý: `rotateRight(Y)` -> `rotateLeft(root)` - Nhận xét: + Các thao tác có độ phức tạp $O(\log_2(n))$. + Với cây cân bằng trung bình 2 lần thêm vào cây thì cần một lần cân bằng lại; 5 lần hủy thì cần một lần cân bằng lại. + Nhưng khi ta thêm rất nhiều Node vào cây thì sẽ khiến cây phải quay (cân bằng) liên tục. Cây có càng nhiều phần tử thì việc cân bằng lại cây sẽ càng mất công hơn. Cây đỏ đen sẽ khắc phục yếu điểm này. [Minh họa thuật toán ở đây](https://visualgo.net/en/bst) ## Cây đỏ đen (Red-black tree) - Là cây tìm kiếm nhị phân (BST) tự cân bằng thỏa mãn các tính chất sau: + Một nút hoặc là đỏ hoặc là đen. + Gốc là đen. + Tất cả các lá (NULL) là đen. + Cả hai con của mọi nút đỏ là đen. (và suy ra mọi nút đỏ có nút cha là đen) + Tất cả các đường đi từ một nút bất kỳ tới các lá có số nút đen bằng nhau. ### Ví dụ [Tại đây](https://www.cs.usfca.edu/~galles/visualization/RedBlack.html) ### Các thao tác trên cây #### Tìm kiếm Giống với [tìm kiếm trong cây nhị phân tìm kiếm](#Tìm-kiếm-một-phần-tử) #### Thêm phần tử Gọi phần tử được thêm vào là $X$ - $X$ sẽ là nút đỏ. - Nếu $X$ là gốc, chuyển $X$ thành màu đen. - Nếu như cha của $X$ màu đỏ. - Nếu như bác của $X$ (anh em với cha của $X$) màu đỏ, chuyển màu của cha và bác thành đen, chuyển màu ông của $X$ (cha của cha $X$) thành đỏ, tiếp tục với ông của $X$. - Nếu như bác của $X$ màu đen, ta có 4 trường hợp xoay cây giống với cây AVL. Với trường hợp trái trái và phải phải, sau khi xoay cây thì ta sẽ tráo đổi màu của ông và cha của $X$. Trường hợp trái phải và phải trái thì ta sẽ tráo đổi màu của ông của $X$ với $X$. ## Cây phân trang ### Khái niệm - Là cây M-phân tìm kiếm. - $\displaystyle\left\lceil {\frac{M}{2}} \right\rceil \le$ số cây con mà mỗi node (trừ gốc và lá) có thể chứa $\le M$. - $\displaystyle\left\lceil {\frac{M}{2}} \right\rceil - 1 \le$ số khoá mà mỗi node (trừ gốc) có thể có $\le M - 1$. - $1 \le$ Số khoá mà node gốc có thể có $M - 1$. - Trong mỗi node, các khoá được sắp xếp tăng dần. - Các node lá nằm cùng mức. - Các khoá trong node con $C_x$ sẽ lớn hơn khoá nàm trước nó và nhỏ hơn khoá nằm sau nó. ### Ví dụ ![](https://hackmd.io/_uploads/H1CBuI1_h.png) ![](https://images.ctfassets.net/piwi0eufbb2g/65O3MMsGuTqX4eiLdgJ6H/dd312f46c2f3842ee83a6629388b304b/b-tree_article_banner.png?w=1200&h=630) [Tại đây](https://www.cs.usfca.edu/~galles/visualization/BTree.html) ### Các thao tác #### Tìm kiếm - Bắt đầu với các khoá trên node gốc. - Nếu $K_i < x < K_{i + 1}$, tìm kiếm bên trong cây con ở giữa $K_i$ và $K_{i + 1}$. - Nếu $K_{M} < X$, tìm kiếm ở cây con bên phải cùng. - Nếu $K_1 > X$, tìm kiếm ở cây con bên trái cùng. - Nếu đã duyệt hết nhưng không tìm thấy, không tồn tại khoá và node giứa giá trị $X$. #### Thêm khoá - Thêm khoá mới vào các lá - Nếu node chưa đầy khoá, thêm khoá vào node. - Nếu node đã đầy, thực hiện tách node. + Khoá trung vị của node sẽ được đưa lên node cha. + 2 phần còn lại sẽ thành 2 cây con được nối lên node cha trong cùng mức. #### Xoá khoá - Nếu khoá nằm trên lá, xoá bình thường. - Nếu vi phạm quy tắc hoặc node cần xoá không phải lá, ta sẽ tìm khoá thay thế. Thường là khoá trái nhất ở cây con bên phải và ngược lại.

    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