二叉搜索树

2021/9/14 23:09:47

本文主要是介绍二叉搜索树,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

#include<iostream>
#include<vector>
using namespace std;
struct TreeNode
{
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(int x) :val(x), left(nullptr), right(nullptr) {}
};
class SearchTree
{
private:
	int _a;
public:
	void sum(int a)
	{
		_a = a;
	}
	void pri()
	{
		sum(5);
		cout << _a << endl;
	}
	void Insert_Node(TreeNode*& root, int val)
	{
		if (nullptr == root) {
			root = new TreeNode(val);
			return;
		}

		if (root->val < val)
		{
			if (root->right == nullptr)
			{
				root->right = new TreeNode(val);
			}
			else
			{
				Insert_Node(root->right, val);
			}
		}
		else if (root->val > val)
		{
			if (root->left == nullptr)
			{
				root->left = new TreeNode(val);
			}
			else
			{
				Insert_Node(root->left, val);
			}
		}
	}
	//根据数组构建一颗二叉搜索树
	TreeNode* Create_SearchTree(vector<int>& vec)
	{

		TreeNode* root = nullptr;
		int length = vec.size();
		for (int i = 0; i < length; i++)
		{
			Insert_Node(root, vec[i]);
		}
		return root;
	}
	void print(TreeNode*& root)
	{
		if (root == nullptr)
		{
			return;
		}
		
		print(root->left);
		cout << root->val << endl;
		print(root->right);
	}
};
int main()
{
	SearchTree tree;
	vector<int> vec{ 23,2,8,1,24,56,98,45};
	TreeNode* root = tree.Create_SearchTree(vec);
	tree.print(root);
	//tree.pri();
}

//遇到的问题
//关于私有成员和公有有成员不熟悉
私有:不能继承,外部不能访问
保护:可以继承,外部不能访问
公有:都可



这篇关于二叉搜索树的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程