二叉树是一种非线性的数据结构。
//定义二叉树
struct Binary_tree
{
char m_data; //节点存放的数据
Binary_tree *m_left; //左子树节点指针
Binary_tree *m_right; //右子树节点指针
};
//二叉树初始化
Binary_tree * My_Init(char data)
{
Binary_tree * m_node;
m_node = new Binary_tree;
m_node->m_data = data;
m_node->m_left = NULL;
m_node->m_right = NULL;
if (m_node != NULL)
return m_node;
else
return NULL;
}
//二叉树查找
Binary_tree * My_find(Binary_tree * treenode,char data)
{
Binary_tree *ptr;
if (treenode == NULL)
return NULL;
else
{
if (data == treenode->m_data)
return treenode;
else
{
if (ptr = My_find(treenode->m_left, data))
return ptr;
else if (ptr = My_find(treenode->m_right, data))
return ptr;
else
return NULL;
}
}
}
//二叉树插入节点
void My_insert(Binary_tree *parent_node, char parent_data,string type,char insert_data)
{
Binary_tree *pnode, *parent;
pnode = new Binary_tree;
pnode->m_left = NULL;
pnode->m_right = NULL;
pnode->m_data = insert_data;
parent = My_find(parent_node, parent_data);
if (!parent)
{
delete pnode;
cout << "the parent tree node is NULL" << endl;
return;
}
if (type == "left")
{
cout << "add the node to the left" << endl;
if (parent->m_left)
cout << "the left node is not NULL" << endl;
else
{
parent->m_left = pnode;
cout << "node add ok" << endl;
}
}
else if (type == "right")
{
cout << "add the node to the right" << endl;
if (parent->m_right)
cout << "the right node is not NULL" << endl;
else
{
parent->m_right = pnode;
cout << "node add ok" << endl;
}
}
else
cout << "parameter is error" << endl;
}
int My_depth(Binary_tree *treenode)
{
int depleft, depright;
if (!treenode)
return 0;
else
{
depleft = My_depth(treenode->m_left);
depright = My_depth(treenode->m_right);
return depleft >= depright ? depleft + 1 : depright + 1;
}
}
//二叉树前序遍历
void My_show(Binary_tree *treenode)
{
if (treenode)
{
cout << treenode->m_data << endl;
My_show(treenode->m_left);
My_show(treenode->m_right);
}
}