C++实现二叉树的前中后层序遍历(递归和迭代)
参考以下图解,这个文章写得真好
————————————————
版权声明:本文为CSDN博主「Monster_ii」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/monster_ii/article/details/82115772
// PrintFromTopToBottom.cpp : 定义控制台应用程序的入口点。
//层序遍历,利用队列的先进先出,即二叉树的广度遍历
//回顾:前中后序遍历,递归或者迭代(利用栈后进先出)
#include "stdafx.h"
#include <vector>
#include <queue>
#include <stack>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
//层序递归遍历(Recursive)
static vector<vector<int>> levelOrder(TreeNode *root) {
vector<vector<int>> res;
levelorder(root, 0, res);
return res;
}
static void levelorder(TreeNode *root, int level, ve