🎯 Mục tiêu
- Hiểu cấu trúc cây và cách duyệt (inorder, preorder, postorder).
- Áp dụng nguyên lý BST để tìm kiếm nhanh.
📘 Lý thuyết
Cây nhị phân gồm các nút, mỗi nút có tối đa 2 con. BST thỏa: giá trị bên trái < nút gốc < giá trị bên phải.
💻 Ví dụ
C++
#include
using namespace std;
struct Node{int val;Node* left;Node* right;Node(int v):val(v),left(NULL),right(NULL){}};
Node* insert(Node* r,int v){
if(!r) return new Node(v);
if(vval) r->left=insert(r->left,v);
else r->right=insert(r->right,v);
return r;
}
void inorder(Node* r){if(!r)return;inorder(r->left);cout<val<<" ";inorder(r->right);}
int main(){Node* root=NULL;for(int x:{5,3,7,2,4,6,8}) root=insert(root,x);inorder(root);}
Python
class Node:
def __init__(self,val): self.val=val;self.left=self.right=None
def insert(r,v):
if not r: return Node(v)
if v
🧩 Bài tập
- Viết hàm tìm kiếm trong BST.
- Đếm số lá trong cây.
- In cây theo thứ tự giảm dần.
💡 Lời giải 1 (tìm kiếm)
def search(root,x):
if not root: return False
if root.val==x: return True
return search(root.left,x) if x
💳 Quét mã ủng hộ tuỳ tâm nhé!