コード例 #1
0
ファイル: bst.cpp プロジェクト: GoodGuySteve/SchoolProjects
T BST<T>::remove_root() {

	if (root == NULL) throw 3; //no root

	T retData = root->get_data();
	T maxData;
	BinaryNode<T>* tmpNode;

	if (root->get_lhs() == NULL){
		BinaryNode<T> *tmpRoot = root;
		root = root->get_rhs();
		delete tmpRoot;
		return retData;
	}

	tmpNode = find_max(root->get_lhs());
	maxData = tmpNode->get_data();
	if(remove(maxData) != maxData) throw 2; //removed the wrong data
	root->set_data(maxData);
	return retData;

	throw 1;
}
コード例 #2
0
ファイル: bst.cpp プロジェクト: GoodGuySteve/SchoolProjects
T BST<T>::remove(T item) {
	
		// 	remember to take care of the root case

	BinaryNode<T> *our_parent = NULL;
	BinaryNode<T> *our_guy = root;
	BinaryNode<T> *tmp;
	T our_data;

	while (our_guy != NULL) {  // Traverse the tree down some path
		if (item == our_guy->get_data())
			break;
		else if (item < our_guy->get_data()){  // Go left
			our_parent = our_guy;
			our_guy = our_guy->get_lhs();
		}
		else{  // Go right
			our_parent = our_guy;
			our_guy = our_guy->get_rhs();
		}
	}

	if (our_guy == NULL){
		throw 1; // item not found
		return our_data; //VS
	}
	//now we know our item is inside our BST


	// NOW WE CAN GET TO OUR 3 CASES OF DELETING. WOOOO
	our_data = our_guy->get_data();

	if (our_guy == root){
		our_data = remove_root();
		return our_data;
	}

	if (our_guy->get_rhs() == NULL && our_guy->get_lhs() == NULL){ //no children lol
		if (our_parent->get_rhs() == our_guy){ //we want to NULL the rhs
			delete our_parent->get_rhs();
			our_parent->set_rhs(NULL);
			return our_data;
		}

		else{ //else, NULL lhs
			delete our_parent->get_lhs();
			our_parent->set_lhs(NULL);
			return our_data;
		}
	}

	else if (our_guy->get_rhs() == NULL && our_guy->get_lhs() != NULL){ // one child -> our lhs is a kid

		tmp = our_guy->get_lhs(); //saved the child in tmp
		
		if (our_parent->get_rhs() == our_guy){
			delete our_parent->get_rhs();
			our_parent->set_rhs(tmp);
			return our_data;

		}

		else{ //else, NULL lhs
			delete our_parent->get_lhs();
			our_parent->set_lhs(tmp);
			return our_data;
		}

	}

	else if (our_guy->get_lhs() == NULL && our_guy->get_rhs() != NULL){

		tmp = our_guy->get_rhs(); //saved the child in tmp 

		if (our_parent->get_rhs() == our_guy){
			delete our_parent->get_rhs();
			our_parent->set_rhs(tmp);
			return our_data;

		}

		else{ //else, NULL lhs
			delete our_parent->get_lhs();
			our_parent->set_lhs(tmp);
			return our_data;
		}


	}


	else{ //two child case
		// 	saving max data into an int or someshit, then removing max's shit, then overwriting the data

		BinaryNode<T> *max;
		max = find_max(our_guy->get_lhs());
		T max_data = max->get_data();

		remove(max->get_data());




		our_guy->set_data(max_data);


		return our_data;
	}






	// TODO: Implement this function
	throw 1;
}