对于如下图所示的二叉树:
深度优先遍历:ABDECF
广度优先遍历:ABCDEF
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;
struct TreeNode
{
int val;
TreeNode *lchild;
TreeNode *rchild;
TreeNode(int x):val(x),lchild(nullptr),rchild(nullptr){}
};
// 深度优先遍历(DFS)
void DFS(TreeNode* root)
{
if(root == nullptr)
return;
// 根节点入栈
stack<TreeNode *> s;
s.push(root);
// 栈不为空
while(!s.empty())
{
// 取栈顶元素
TreeNode *pNode = s.top();
s.pop();
// 打印根节点
cout << pNode->val << " ";