关闭

二叉查找树

标签: c++数据结构算法
229人阅读 评论(0) 收藏 举报
分类:

-BinarySearchTree.h

#ifndef __BINARY_SEARCH_TREE_H__
#define __BINARY_SEARCH_TREE_H__

#include <iostream>
#include <string>

template <class Object, class Comparator = std::less<Object> >
class BinarySearchTree {

public:
	BinarySearchTree();
	BinarySearchTree(const BinarySearchTree& rhs);
	~BinarySearchTree();

	const Object& findMin()const;
	const Object& findMax()const;
	bool contains(const Object& x)const;
	bool isEmpty()const { return NULL == root; }
	void printTree()const;

	void makeEmpty();
	void insert(const Object& x);
	void remove(const Object& x);

	const BinarySearchTree& operator=(const BinarySearchTree& rhs);

private:
	struct BinaryNode {
		Object element;
		BinaryNode* left;
		BinaryNode* right;

		BinaryNode(const Object& theElement, BinaryNode* lt, BinaryNode* rt) :
			element(theElement), left(lt), right(rt) {}
	};

	BinaryNode* root;
	Comparator isLessThan;
	
	BinaryNode* findMin(BinaryNode* t)const;
	BinaryNode* findMax(BinaryNode* t)const;
	bool contains(const Object& x, BinaryNode* t)const;
	void printTree(BinaryNode* t)const;
	void insert(const Object& x, BinaryNode*& t)const;
	void remove(const Object& x, BinaryNode*& t)const;
	void makeEmpty(BinaryNode*& t);
	BinaryNode* clone(BinaryNode* t)const;

};


// constructor
template <class Object, class Comparator>
BinarySearchTree<Object, Comparator>::BinarySearchTree() {
	root = NULL;
}

// copy constructor
template <class Object, class Comparator>
BinarySearchTree<Object, Comparator>::BinarySearchTree(const BinarySearchTree& rhs) {
	root = rhs.clone(rhs.root);
}

// destructor
template <class Object, class Comparator>
BinarySearchTree<Object, Comparator>::~BinarySearchTree() {
	makeEmpty();
}

/**
 * Returns true if x is found in the tree
 */
template <class Object, class Comparator>
bool BinarySearchTree<Object, Comparator>::contains(const Object& x)const {
	return contains(x, root);
}

/**
 * Internal method to test if an item is in a subtree
 * x is item to search for
 * t is the node that roots the subtree 
 */
template <class Object, class Comparator>
bool BinarySearchTree<Object, Comparator>::contains(const Object& x, BinaryNode* t)const {

	if (t == NULL)
		return false;
	else if (isLessThan(x, t->element))
		return contains(x, t->left);
	else if (isLessThan(t->element, x))
		return contains(x, t->right);
	else
		return true;	// Match
}

/**
 * Insert x into the tree; duplicates are ignored
 */
template <class Object, class Comparator>
void BinarySearchTree<Object, Comparator>::insert(const Object& x) {
	insert(x, root);
}

/**
 * Internal method to insert into a subtree
 * x is the item to insert
 * t is the node that roots the subtree
 * Set the new root of the subtree
 */
template <class Object, class Comparator>
void BinarySearchTree<Object, Comparator>::insert(const Object& x, BinaryNode*& t)const {
	//root = new BinaryNode(2, NULL, NULL);
	if (t == NULL)
		t = new BinaryNode(x, NULL, NULL);
	else if (isLessThan(x, t->element))
		insert(x, t->left);
	else if (isLessThan(t->element, x))
		insert(x, t->right);
	else
		return;
}

/**
* Return the smallest item
*/
template <class Object, class Comparator>
const Object& BinarySearchTree<Object, Comparator>::findMin()const {

	BinaryNode* node = findMin(root);

	if (NULL == node) throw out_of_range("BinarySearchTree is empty.");

	else return node->element;

}

/**
 * Internal method to find the smallest item in a subtree t.
 * Return node containing the smallest item
 */
template <class Object, class Comparator>
typename BinarySearchTree<Object, Comparator>::BinaryNode*
BinarySearchTree<Object, Comparator>::findMin(BinaryNode* t)const {
	
	if (t == NULL)
		return NULL;
	else if (t->left == NULL)
		return t;
	return findMin(t->left);
}

/**
* Return the largest item
*/
template <class Object, class Comparator>
const Object& BinarySearchTree<Object, Comparator>::findMax()const {

	BinaryNode* node = findMax(root);

	if (NULL == node) throw out_of_range("BinarySearchTree is empty.");

	else return node->element;
}

/**
 * Internal method to find the largest item in a subtree t.
 * Return node containing the largest item
 */
template <class Object, class Comparator>
typename BinarySearchTree<Object, Comparator>::BinaryNode*
BinarySearchTree<Object, Comparator>::findMax(BinaryNode* t)const {
	
	if (t == NULL)
		return NULL;
	else if (t->right == NULL)
		return t;
	return findMax(t->right);
}

/**
 * Remove x from the tree
 */
template <class Object, class Comparator>
void BinarySearchTree<Object, Comparator>::remove(const Object& x) {
	remove(x, root);
}

/**
 * Internal method to remove from a subtree
 * x is the item to remove
 * t is the node that roots the subtree
 * Set the new root of the subtree
 */
template <class Object, class Comparator>
void BinarySearchTree<Object, Comparator>::remove(const Object& x, BinaryNode*& t)const {

	if (NULL == t)
		return;
	else if (isLessThan(x, t->element))
		remove(x, t->left);
	else if (isLessThan(t->element, x))
		remove(x, t->right);
	else if (NULL != t->left && NULL != t->right) {		// there are both left son and right son
		// 用结点t的右子树的最小结点来替代t
		// 再递归调用从t的右子数中删除t->element这个结点
		t->element = findMin(t->right)->element;
		remove(t->element, t->right);
	}
	else {
		BinaryNode* oldNode = t;
		t = (t->left != NULL) ? t->left : t->right;
		delete oldNode;
	}
}

// makeEmpty
template <class Object, class Comparator>
void BinarySearchTree<Object, Comparator>::makeEmpty() {
	makeEmpty(root);
}

/**
 * Internal method to make subtree empty
 */
template <class Object, class Comparator>
void BinarySearchTree<Object, Comparator>::makeEmpty(BinaryNode*& t) {

	if (t != NULL) {
		makeEmpty(t->left);
		makeEmpty(t->right);
		delete t;
	}
	t = NULL;
}

/**
 * Deep Copy
 */
template <class Object, class Comparator>
const BinarySearchTree<Object, Comparator>& 
BinarySearchTree<Object, Comparator>::operator=(const BinarySearchTree<Object, Comparator>& rhs) {

	if (this != &rhs) {
		this->makeEmpty();
		this->root = rhs.clone(rhs.root);
	}
	return *this;
}

/**
 * Internal method to clone subtree 
 */
template <class Object, class Comparator>
typename BinarySearchTree<Object, Comparator>::BinaryNode* 
BinarySearchTree<Object, Comparator>::clone(BinaryNode* t)const {

	if (t == NULL) return NULL;

	else return new BinaryNode(t->element, clone(t->left), clone(t->right));

}

/**
 * Print the subtree
 */
template <class Object, class Comparator>
void BinarySearchTree<Object, Comparator>::printTree()const {
	printTree(root);
}

/** 
 * Internal method to print the subtree
 */
template <class Object, class Comparator>
void BinarySearchTree<Object, Comparator>::printTree(BinaryNode* t)const {

	if (t == NULL) return;
	printTree(t->left);
	printTree(t->right);
	std::cout << t->element << " ";

}



#endif



-main.cpp

#include "BinarySearchTree.h"
using namespace std;

void printTree(BinarySearchTree<int>& ibst, string s);

int main()
{

	BinarySearchTree<int> ibst;

	ibst.insert(6);
	ibst.insert(2);
	ibst.insert(1);
	ibst.insert(8);
	ibst.insert(7);
	ibst.insert(100);

	BinarySearchTree<int> ibst2(ibst);
	printTree(ibst2, "ibst2");

	ibst.remove(7);
	ibst.remove(100);
	
	BinarySearchTree<int> ibst3 = ibst;
	printTree(ibst3, "ibst3");

	ibst.insert(4);
	ibst.insert(3);
	printTree(ibst, "ibst");

	if (ibst.contains(6)) cout << "ibst contains 6" << endl;
	else cout << "ibst doesn't contain 6" << endl;
	if (ibst.contains(10)) cout << "ibst contains 10" << endl;
	else cout << "ibst doesn't contain 10" << endl;

	if (!ibst.isEmpty()) cout << "ibst isn't empty" << endl;
	else cout << "ibst is empty" << endl;
	ibst.makeEmpty();
	if (!ibst.isEmpty()) cout << "ibst isn't empty" << endl;
	else cout << "ibst is empty" << endl;

	system("pause");
	return 0;
}

void printTree(BinarySearchTree<int>& ibst, string s) {
	cout << s << ": ";
	ibst.printTree();
	cout << endl;
	cout << s << ".max: " << ibst.findMax()
		<< "  " << s << ".min: " << ibst.findMin();
	cout << endl << endl;
}



0
0
查看评论

数据结构-二叉树和二叉查找树

先按树-二叉树-二叉查找树的顺序解释会比较清楚。 一,树 树(Tree)是n(n≥0)个结点的有限集。在任意一棵非空树中: (1)有且仅有一个特定的被称为根(Root)的结点; (2)当n>1时,其余结点可分为m(m>0)个互不相交的有限集T1,T2,…,Tm,其中每一个集合本身...
  • tuke_tuke
  • tuke_tuke
  • 2015-12-20 17:44
  • 2167

从二叉查找树到平衡二叉树再到红黑树

从二叉查找树到平衡二叉树再到红黑树的分析与实现
  • guimingyue
  • guimingyue
  • 2014-04-12 11:10
  • 1672

二叉查找树的应用

二叉查找树又称为二叉排序树, 它或者是一棵空树;或者是具有下列性质的二叉树:      (1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;      (2)若右子树不空,则右子树上所有结点...
  • liuhuiyi
  • liuhuiyi
  • 2012-07-17 14:34
  • 1061

lintcode validate-binary-search-tree 验证二叉查找树

问题描述lintcode笔记 代码1是用到中序遍历,要求中序遍历是严格的增序。用到了辅助空间。 代码2是leetcode上面的解法,用到了prev指针记录前一个节点,省下了辅助空间,而且要注意prev传进去还应该是引用。 代码1/** * Definition of TreeNode: * cl...
  • waltonhuang
  • waltonhuang
  • 2016-07-22 17:03
  • 385

二叉查找树的非递归操作

昨天同学去参加阿里巴巴面试,被问到二叉树的一些基本问题,分享一下: 1.如何非递归dfs求得树的深度 2.如何非递归bfs求得树的深度 *3.如何非递归地中前后序遍历二叉查找树。 二叉树写过不下十次了,但是基本每次都是用递归来写,一时间问道还不能一下写出来。 问题二还是比较好写,一的话可能...
  • u011044759
  • u011044759
  • 2014-09-18 15:32
  • 2525

1564: [NOI2009]二叉查找树 区间DP

DP太弱了。。不会做T T这题的条件非常多也非常乱,所以我们要先挖掘一些性质,尽量的找到一个解决问题的顺序。可以发现所谓的数据值和权值其实就是一棵treap,改变权值相当于treap的旋转,由于数据值不变,所以中序遍历是不变的,所以我们可以按数据值排序,得到树的中序遍历。并且我们发现权值可以取所有实...
  • Phenix_2015
  • Phenix_2015
  • 2016-03-14 15:28
  • 280

动态规划4-最优二叉查找树

前面说过动态规划最典型的就是解决最优化问题的(具有最优子结构的最优化问题),最优二叉查找树就是一个典型的最优化问题。 问题描述: 给定一个n元素的中序序列,它可以有卡特兰数个不同形状的二叉排序树。(卡特兰数的定义及证明参见组合数学): ,如果我们知道每个键的查找概率,怎么来构造一个平均查...
  • mengzhejin
  • mengzhejin
  • 2014-07-16 16:25
  • 2006

Java-如何创建二叉查找树

这篇文章主要讲如何创建二叉查找树。如果有哪些不对的地方请指正,欢迎批评和建议。要点本文将依照一下的几点介绍 什么是二叉查找数 二叉查找树的遍历 代码例子
  • xiaoxiaoxuanao
  • xiaoxiaoxuanao
  • 2017-03-13 07:35
  • 443

LintCode 11-二叉查找树中搜索区间

本人电子系,只为一学生。心喜计算机,小编以怡情。给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。 思路:...
  • Jason__Liang
  • Jason__Liang
  • 2017-01-05 19:41
  • 239

二叉查找树的基本例程

使二叉树为二叉查找树(Binary Search Tree)的性质是:对于树中的每个节点X,它的左子树中所有关键字值小于X的关键字值,而它的右子树中所有关键字值大于X的关键字值。         以下为BinaryTree的基本实现例程,大部分...
  • xiahouzuoxin
  • xiahouzuoxin
  • 2012-11-07 20:13
  • 1872
    个人资料
    • 访问:72546次
    • 积分:2234
    • 等级:
    • 排名:第19852名
    • 原创:139篇
    • 转载:124篇
    • 译文:0篇
    • 评论:9条
    最新评论