二叉搜索树专题1 二叉查找树的建立
原创 于 2023-11-05 10:03:30 发布 · 粉丝可见 · 191 阅读 · 0 · 0 · 本内容遵循CC 4.0 BY-SA版权协议 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 GEO检测 · 编辑
文章链接:https://blog.csdn.net/hacker_51/article/details/134224649
题目:

样例:
cobol<br/>6<br/>5 2 3 6 1 8<br/> |

思路:
二叉搜索树的建立,需要了解二叉搜索树的性质。
根据所给的序列进行按序插入即可。
代码详解如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include <iostream> #include <vector> #include <queue> #include <cstring> #include <algorithm> #include <unordered_map> #define endl '\n' #define YES puts("YES") #define NO puts("NO") #define umap unordered_map #define All(x) x.begin(),x.end() #pragma GCC optimize(3,"Ofast","inline") #define IOS std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0) using namespace std; const int N = 2e6 + 10; int n; umap<int,int>l,r;
void Insert(int& root,int x) { if(!root) { root = x; return ; } if(root > x) Insert(l[root],x); else Insert(r[root],x); } void Preorder(int root) { if(root) { cout << root; if(--n) cout << ' '; Preorder(l[root]); Preorder(r[root]); } } inline void solve() { int root; cin >> n; for(int i = 0,x;i < n;++i) { cin >> x; if(!i) root = x; else Insert(root,x); } Preorder(root); } int main() {
IOS; int _t = 1;
while (_t--) { solve(); } return 0; }
|
最后提交:
