二叉树的类实现和递归遍历思路

#ifndef BINTREE_H
#define BINTREE_H
#include //提供size_t
template//表示这个是类模板
class binary_tree_node {
public:
	typedef Item value_type;
	binary_tree_node(const Item& init_data = Item(), binary_tree_node* init_left = NULL, binary_tree_node* init_right = NULL) {
		data_field = init_data;
		left_field = init_left;
		right_field = init_right;
	}
	Item& data() { return data_field; }
	binary_tree_node* left() { return left_field; }
	binary_tree_node* right() { return right_field; }
    //使用const引用不需要拷贝一次,也不会在函数实现中修改其值,又快又安全
	void set_data(const Item& new_data) { data_field = new_data; }
	void set_left(binary_tree_node* new_left) { left_field = new_left; }
	void set_right(binary_tree_node* new_right) { right_field = new_right; }
	bool is_leaf()const {
		return (left_field == NULL) && (right_field == NULL);
	}
private:
	Item data_field;
	binary_tree_node* left_field;
	binary_tree_node* right_field;
};

template
void preorder(binary_tree_node* node_ptr) {
	if (node_ptr != NULL) {
		std::cout << node_ptr->data() << std::endl;
		preorder(node_ptr->left());
		preorder(node_ptr->right());
	}
}
template
void inorder(binary_tree_node* node_ptr) {
	if (node_ptr != NULL) {
		inorder(node_ptr->left());
		std::cout << node_ptr->data() << std::endl;
		inorder(node_ptr->right());
	}
}
template
void postorder(binary_tree_node* node_ptr) {
	if (node_ptr != NULL) {
		postorder(node_ptr->left());
		postorder(node_ptr->right());
		std::cout << node_ptr->data() << std::endl;
	}
}
//清除一颗二叉树
template
void tree_clear(binary_tree_node*& root_ptr) {
	if (root_ptr != NULL) {
		tree_clear(root_ptr->left());
		tree_clear(root_ptr->right());
		delete root_ptr;
		root_ptr = NULL;
	}
}
//复制一颗二叉树
template
binary_tree_node* tree_copy(const binary_tree_node* root_ptr) {
	binary_tree_node* l_ptr;
	binary_tree_node* r_ptr;
	if (root_ptr == NULL) {
		return NULL;
	}
	else {
		l_ptr = tree_copy(root_ptr->left());
		r_ptr = tree_copy(root_ptr->right());
		return new binary_tree_node(root_ptr->data(), l_ptr, r_ptr);
	}
}
//返回二叉树的节点个数
template
std::size_t tree_size(const binary_tree_node* node_ptr) {
	if (node_ptr == NULL) {
		return 0;
	}
	else {
		return 1 + tree_size(node_ptr->left() + tree_size(node_ptr->right()));
	}
}

#endif

 

 

你可能感兴趣的:(数据结构基础)