#include<iostream>
#include<stack>
#include<stdio.h>
#include<vector>
using namespace std;
class TreeNode
{
public :
char val;
TreeNode* lchild;
TreeNode* rchild;
};
//非递归前序遍历
class Solution {
public:
//前序
vector<char> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<char> result;
if (root == NULL) return result;
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top(); // 中
st.pop();
result.push_back(node->val);
if (node->rchild) st.push(node->rchild); // 右(空节点不入栈)
if (node->lchild) st.push(node->lchild); // 左(空节点不入栈)
}
return result;
}
//中序
vector<char> inorderTraversal(TreeNode* root) {
vector<char> result;
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur != NULL || !st.empty()) {
if (cur != NULL) { // 指针来访问节点,访问到最底层
st.push(cur); // 将访问的节点放进栈
cur = cur->lchild; // 左
}
else {
cur = st.top(); // 从栈里弹出的数据,就是要处理的数据(放进result数组里的数据)
st.pop();
result.push_back(cur->val); // 中
cur = cur->rchild; // 右
}
}
return result;
}
//后序
vector<char> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<char> result;
if (root == NULL) return result;
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
result.push_back(node->val);
if (node->lchild) st.push(node->lchild); // 相对于前序遍历,这更改一下入栈顺序 (空节点不入栈)
if (node->rchild) st.push(node->rchild); // 空节点不入栈
}
reverse(result.begin(), result.end()); // 将结果反转之后就是左右中的顺序了
return result;
}
//递归
void preorder(TreeNode *root)
{
if (root == NULL)
{
return;
}
cout << root->val<< endl;
//递归遍历左子树
preorder(root->lchild);
//递归遍历左子树
preorder(root->rchild);
}
};
int main()
{
TreeNode node1 = { 'A',NULL,NULL };
TreeNode node2 = { 'B',NULL,NULL };
TreeNode node3 = { 'C',NULL,NULL };
TreeNode node4 = { 'D',NULL,NULL };
TreeNode node5 = { 'E',NULL,NULL };
TreeNode node6 = { 'F',NULL,NULL };
TreeNode node7 = { 'G',NULL,NULL };
TreeNode node8 = { 'H',NULL,NULL };
//建立结点关系
node1.lchild = &node2;
node1.rchild = &node6;
node2.rchild = &node3;
node3.lchild = &node4;
node3.rchild = &node5;
node6.rchild = &node7;
node7.lchild = &node8;
Solution s1;
vector<char>v1,v2;
v1=s1.preorderTraversal(&node1);
cout << v1.size() << endl;
for (int i = 0; i < v1.size()-1; i++)
{
cout << v1[i];
}
cout << endl;
v2 = s1.inorderTraversal(&node1);
cout << v2.size() << endl;
for (int i = 0; i < v2.size() - 1; i++)
{
cout << v2[i];
}
}
二叉树的三种非递归遍历
最新推荐文章于 2021-10-29 22:37:45 发布