目录
树的遍历
树的遍历顺序
树的遍历顺序
前序遍历:中->左->右
中序遍历:左->中->右
后序遍历:左->右->中
树的递归遍历
递归定义规则:
1.确定返回值和参数
2.确定终止条件
3.构造单层的递归逻辑
树递归:
返回值:无需返回,参数是当前的树结点。
终止条件:当结点为空时返回根节点。
单层逻辑:按照树顺序遍历
#include<cstdio>
#include<algorithm>
#include<cctype>
#include<string>
#include <iostream>
#include<stack>
#include <queue>
using namespace std;
struct node
{
char data;
node* lchild;
node* rchild;
};
node* create()
{
char ch;
node* root;
root = new node;
cin >> ch;
if (ch == '#')
root = NULL;
else
{
root->data = ch;
root->lchild = create();
root->rchild = create();
}
return root;
}
void inorder(node* root)
{
if (root == NULL)
return;
inorder(root->lchild);
cout << root->data;
inorder(root->rchild);
}
vector<char>inorder_1(node* root)
{
vector<char>res;
stack<node*>st;
while (root != NULL || !st.empty())
{
while (root != NULL)
{
st.push(root);
root = root->lchild;
}
root = st.top();
st.pop();
res.push_back(root->data);
root = root->rchild;
}
return res;
}
vector<char>preorder_1(node* root)
{
vector<char>res;
stack<node*>st;
if (root == nullptr)
return res;
node* cur = root;
while (!st.empty() || cur != nullptr)
{
while (cur != nullptr)
{
res.push_back(cur->data);
st.push(cur);
cur = cur->lchild;
}
cur = st.top();
st.pop();
cur = cur->rchild;
}
return res;
}
vector<char>postorder_1(node* root)
{
vector<char>res;
if (root == NULL)
return res;
stack<node*>st;
node* pre = nullptr;
while (root != NULL || !st.empty())
{
while (root != nullptr)
{
st.push(root);
root = root->lchild;
}
//迭代找到最左结点
root = st.top();
st.pop();
if (root->rchild && root->rchild != pre)//如果右结点存在并且右节点没有被访问过
{
st.push(root);
root = root->rchild;
}
else
{
res.push_back(root->data);
pre = root;//防止重复访问右子树
root = nullptr;//防止重复访问左子树
}
}
return res;
}
vector<vector<char>>layer_order1(node* root)
{
queue<node*>que;
if (root != nullptr)que.push(root);
vector<vector<char>>res;
while (!que.empty())
{
int size = que.size();
vector<char>vec;
for (int i = 0; i < size; i++)
{
node* temp = que.front();
que.pop();
vec.push_back(temp->data);
if (temp->lchild)que.push(temp->lchild);
if (temp->rchild)que.push(temp->rchild);
}
}
return res;
}
int max_Depth(node* root)//求二叉树最大深度(高度)
{
if(root==nullptr)
{
return 0;
}
else
return max(max_Depth(root->left),max_Depth(root->right))+1;
}
int main()
{
node* root;
vector<char>vec;
cout << "这棵树为\n";
root = create();
vec=postorder_1(root);
for (auto i = 0; i < vec.size(); i++)
cout << vec[i] << ' ';
cout << endl;
vec = inorder_1(root);
for (auto i = 0; i < vec.size(); i++)
cout << vec[i] << ' ';
cout << endl;
vec = preorder_1(root);
for (auto i = 0; i < vec.size(); i++)
cout << vec[i] << ' ';
cout << endl;
}