文章目录
- c++代码
- 结果
-
首先实现一颗这样的树
-
然后使用
系统栈(递归)
和自己定义的栈
分别实现二叉树的前序遍历
c++代码
#include<iostream>
#include<stack>
#include<map>
using namespace std;
map<int, char> nodeMap;
struct TreeNode
{
int val_;
TreeNode* left_;
TreeNode* right_;
TreeNode(const int val, TreeNode* left, TreeNode* right) :val_(val), left_(left), right_(right) {}
TreeNode() :TreeNode(0, nullptr, nullptr) {}
TreeNode(const int val) :TreeNode(val, nullptr, nullptr) {}
};
void preorderTraversal(TreeNode* root)
{
if (root == nullptr)
{
return;
}
cout << nodeMap[root->val_] << " ";
preorderTraversal(root->left_);
preorderTraversal(root->right_);
}
void preorderTraversal_customStack(TreeNode* root)
{
stack<TreeNode*> customStack;
customStack.push(root);
while (customStack.empty() == false)
{
// 访问根节点
TreeNode* tmpnode = customStack.top();
customStack.pop();
cout << nodeMap[tmpnode->val_] << " ";
if (tmpnode->right_ != nullptr)
{
// 右节点入栈
customStack.push(tmpnode->right_);
}
if (tmpnode->left_ != nullptr)
{
// 左节点入栈
customStack.push(tmpnode->left_);
}
}
cout << endl;
}
int main()
{
nodeMap[11] = 'A';
nodeMap[9] = 'B';
nodeMap[7] = 'C';
nodeMap[3] = 'D';
nodeMap[5] = 'E';
nodeMap[6] = 'F';
nodeMap[1] = 'G';
nodeMap[2] = 'H';
nodeMap[8] = 'I';
nodeMap[4] = 'J';
nodeMap[10] = 'K';
TreeNode* root = new TreeNode(11);
TreeNode* node1 = new TreeNode(9);
root->left_ = node1;
TreeNode* node2 = new TreeNode(7);
root->right_ = node2;
TreeNode* node3 = new TreeNode(3);
node1->left_ = node3;
TreeNode* node4 = new TreeNode(5);
node1->right_ = node4;
TreeNode* node5 = new TreeNode(6);
node2->left_ = node5;
TreeNode* node6 = new TreeNode(1);
node2->right_ = node6;
TreeNode* node7 = new TreeNode(2);
node3->left_ = node7;
TreeNode* node8 = new TreeNode(8);
node3->right_ = node8;
TreeNode* node9 = new TreeNode(4);
node5->right_ = node9;
TreeNode* node10 = new TreeNode(10);
node6->left_ = node10;
preorderTraversal(root);
cout << endl;
preorderTraversal_customStack(root);
return 0;
}
结果
与预期结果是一致的