目录
6.1 二叉树的创建
先创建节点的结构体,再创建树的类。
节点的结构体如下。
//template<typename T>
template<class T>
struct BinaryTreeNode{
T val;
BinaryTreeNode* left;
BinaryTreeNode* right;
//构造函数
BinaryTreeNode(): left(nullptr), right(nullptr) {}
BinaryTreeNode(T x): val(x), left(nullptr), right(nullptr) {}
BinaryTreeNode(T x, BinaryTreeNode* left, BinareTreeNode* right): val(x), left(left), right(right) {}
}
下面是节点的构造函数,方便在创建数的时候使用。
下面的树使用了模板。
template<typename T>
struct BinaryTreeNode{
T _data;
BinaryTreeNode<T>* _left; //左节点
BinaryTreeNode<T>* _right; //右节点
BinaryTreeNode();
//节点的构造函数,并对其进行初始化,T()为一个匿名对象。
BinaryTreeNode(T data = T()):_left(NULL), _right(NULL), _data(data){}
};
由于会经常用到BinaryTreeNode<T>,重定义为Node。
typedef BinaryTreeNode<T> Node;
写二叉树类的时候,直接给类设置一个根节点,以这个根节点为基础,逐步构建二叉树。
class BinaryTree{
public:
private:
BinaryTreeNode<T>* _root; //根节点
};
6.2 二叉树的遍历
//前序遍历
void prev_order()
{
_prev_order(_root);
cout << endl;
}
void _prev_order(node*root)
{
if (root == NULL)
return;
cout << root->_data << " ";
_prev_order(root->_left);
_prev_order(root->_right);
}
//非递归的前序遍历
void prev_order_no_r()
{
node* cur = _root;
stack<node*>s;
while (cur || !s.empty())
{
while (cur)
{
cout << cur->_data << " ";
s.push(cur);
cur = cur->_left;
}
node* top = s.top();
s.pop();
//子问题
cur = top->_right;
}
cout << endl;
}
//中序遍历
void in_order()
{
_in_order(_root);
cout << endl;
}
void _in_order(node* root)
{
//中序遍历:左子树->根节点->右子树
if (root == NULL)return;
_in_order(root->_left);
cout << root->_data << " ";
_in_order(root->_right);
}
//非递归的中序遍历
void in_order_no_r()
{
node* cur = _root;
stack<node*>s;
while (cur || !s.empty())
{
while (cur)
{
s.push(cur);
cur = cur->_left;
}
node* top = s.top();
cout << top->_data << " ";
s.pop();
cur = top->_right;
}
cout << endl;
}
//后序遍历
void in_order()
{
_in_order(_root);
cout << endl;
}
void _in_order(node* root)
{
//后序遍历:左子树->右子树->根节点
if (root == NULL)return;
_in_order(root->_left);
_in_order(root->_right);
cout << root->_data << " ";
}
//非递归的后序遍历
void post_order_no_r()
{
node* cur = _root;
node*prev = NULL;
stack<node*>s;
while (cur || !s.empty())
{
while (cur)
{
s.push(cur);
cur = cur->_left;
}
node* top = s.top();
if (top->_right == NULL || top->_right == prev)
{
cout << top->_data << " ";
s.pop();
prev = top;
}
else
{
cur = top->_right;
}
}
cout << endl;
}
6.3 平衡二叉树
6.4 二叉查找树
6.5 平衡二叉查找树
6.5.1 AVL树
6.5.2 红黑树