//前序遍历:根节点->左子树->右子树
//中序遍历:左子树->根节点->右子树
//后序遍历:左子树->右子树->根节点
//定义数据类型可以用泛型
struct Data
{
int hp;
};
//树的节点
struct Node
{
Data data;
Node* left;
Node* right;
Node(int num):left(NULL),right(NULL)
{
data.hp = num;
}
Node(){ data.hp = num; }
};
class Tree
{
public:
Tree():root(NULL),len(0){}
~Tree(){}
Node* root;
void addNode(int num);
void qian();
void digui_qian(Node* node);
void zhong();
void digui_zhong(Node* node);
void hou();
void digui_hou(Node* node);
void ceng();
private:
int len;
vector<Node*> m_vec;
};
//创建
void addNode(int num)
{
len++;
int n = len;
Noed* node = new Node(num);
if(n == 1)
{
root = node;
}
else
{
n = n/2;
if(len%2)
{
m_vec[n-1]->right = node;
}
else
{
m_vec[n-1]->left = node;
}
}
m_vec.push_back(node);
}
//前序遍历:根节点->左子树->右子树
//非递归
void qian()
{
Node* node = root;
stack<Node*> sta;
while(node || sta.size())
{
if(node)
{
cout << node->data.hp << endl;
if(node->right)
sta.push(node->right)
node = node->left;
}
else
{
node = sta.top();
sta.pop();
}
}
}
//递归
void digui_qian(Node* node)
{
if(node)
{
cout << node->date.hp <<endl;
digui_qian(node->left);
digui_qian(node->right);
}
}
//中序遍历:左子树->根节点->右子树
//非递归
void zhong()
{
Node* node = root;
stack<Node*> sta;
while(node || sta.size())
{
if(node)
{
sta.push(node);
node = node->left;
}
else
{
node = sta.top();
sta.pop();
cout << node->data.hp <<endl;
node = node->right;
}
}
}
//递归
void digui_zhong(Node* node)
{
if(node)
{
digui_zhong(node->left);
cout << node->date.hp <<endl;
digui_zhong(node->right);
}
}
//后序遍历:左子树->右子树->根节点
//非递归
void hou()
{
Node* node = root;
Stack<Node*> sta;
while(node || sta.size())
{
if(node)
{
sta.push(node);
node = node->left;
}
else
{
node = sta.top();
sta.pop();
cout << node->data.hp << endl;
while(sta.size() && sta.top()->right == node)
{
node = sta.top();
sta.pop();
cout << node->data.hp <<endl;
}
if(sta.size())
node = sta.top()->right;
else
return;
}
}
}
//后序遍历:左子树->右子树->根节点
//递归
void digui_hou(Node* node)
{
if(node)
{
digui_hou(node->left);
digui_hou(node->right);
cout << node->data.hp <<endl;
}
}
//层序遍历又称广序遍历
//利用单项队列的先进先出
void ceng()
{
Node*temp;
queue<Node*> que;
que.push (root);
while(que.size())
{
temp=que.front();
que.pop();
cout<<temp->data.hp<<endl;
if( temp->left )
que.push( temp->left );
if ( temp->right )
que.push( temp->right );
}
}
二叉树遍历
最新推荐文章于 2023-07-12 17:34:57 发布