二叉搜索树专题1 二叉查找树的建立

编程入门 行业动态 更新时间:2024-10-15 02:32:16

二叉搜索树<a href=https://www.elefans.com/category/jswz/34/1770001.html style=专题1 二叉查找树的建立"/>

二叉搜索树专题1 二叉查找树的建立

题目:

样例:

输入
6
5 2 3 6 1 8
输出
5 2 1 3 6 8

思路:

        二叉搜索树的建立,需要了解二叉搜索树的性质。

二叉搜索树的性质

左孩子结点:   比根节点小

右孩子结点:   比根节点大

根据所给的序列进行按序插入即可。

代码详解如下:

#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;	// 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()
{
//	freopen("a.txt", "r", stdin);IOS;int _t = 1;
//	cin >> _t;while (_t--){solve();}return 0;
}

最后提交:

更多推荐

二叉搜索树专题1 二叉查找树的建立

本文发布于:2023-11-16 14:43:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625351.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:专题

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!