二叉树层序遍历的递归和非递归算法

层序遍历,顾名思义,就是一层一层的遍历,在二叉树中就是从根节点到叶子结点一层层遍历,递归算法比较好理解,非递归算法需要用到队列,先将根节点入队列,输出其节点值,有左右子节点,依次将左右子节点入队列,先入队列的先输出,依此类推。代码实现如下:

#include<iostream>
#include<vector>  
#include<stack>  
#include<queue> 
using namespace std;

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution1 {
public:
	//递归遍历(Recursive Solution)
	static vector<vector<int>> levelOrder(TreeNode *root) {
		vector<vector<int>> res;
		levelorder(root, 0, res);
		return res;
	}
	static void levelorder(TreeNode *root, int level, vector<vector<int>> &res) {
		if (!root) return;
		if (res.size() == level) res.push_back({});
		res[level].push_back(root->val);
		if (root->left) levelorder(root->left, level + 1, res);
		if (root->right) levelorder(root->right, level + 1, res);
	}
};

class Solution2 {
public:
	//迭代遍历(Iterative Solution)
	static vector<vector<int>> levelOrder(TreeNode *root) {
		vector<vector<int>> res;
		if(!root) return res;
		queue<TreeNode*> q;
		q.push(root);
		while(!q.empty()){
			int n=q.size();
			vector<int> onelevel;
			for(int i=0;i<n;i++){
				TreeNode *node=q.front();
				onelevel.push_back(node->val);
				q.pop();
				if(node->left) q.push(node->left);
				if(node->right) q.push(node->right);
			}
			res.push_back(onelevel);
		}
		return res;
	}
};

int main() {
	TreeNode * root = NULL;
	root = new TreeNode(0);
	root->left = new TreeNode(1);
	root->right = new TreeNode(2);
	root->left->left = new TreeNode(3);
	root->left->right = new TreeNode(4);
	root->right->left = new TreeNode(5);
	root->right->right = new TreeNode(6);
	vector<vector<int>> res = Solution1::levelOrder(root);
	for (int i = 0; i<res.size(); i++) {
		for (int j = 0; j<res[i].size(); j++) {
			cout << res[i][j] << ' ';
		}
		cout << endl;
	}
	cout<<endl;
	vector<vector<int>> result = Solution2::levelOrder(root);
	for (int i = 0; i<result.size(); i++) {
		for (int j = 0; j<result[i].size(); j++) {
			cout << result[i][j] << ' ';
		}
		cout << endl;
	}
	//cout<<endl;
	system("pause");
	return 0;
}
    原文作者:递归算法
    原文地址: https://blog.csdn.net/u013146882/article/details/72584312
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞