Binary Search Tree (二元搜尋樹)

#include <bits/stdc++.h> using namespace std; struct node { int v; node *l, *r; node(int _v = 0): v(_v), l(nullptr), r(nullptr) {} } *root = nullptr; void insert(node*& o, int v) { if (!o) o = new node(v); else insert(v >= o->v ? o->r : o->l, v); } bool count(node* o, int v) { if (!o) return 0; else if (o->v == v) return 1; else return count(o->v > v ? o->r : o->l, v); } void pre(node* o) { if (!o) return; cout << o->v << ' ', pre(o->l), pre(o->r); } void in(node* o) { if (!o) return; in(o->l), cout << o->v << ' ', in(o->r); } void post(node* o) { if (!o) return; post(o->l), post(o->r), cout << o->v << ' '; } void traversal(node* o, const string& s) { if (s == "pre") pre(o); else if (s == "in") in(o); else if (s == "post") post(o); cout << '\n'; }
Select a repo