LeetCode102.——二叉树的层次遍历

题目:

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

思路:

广度优先搜索的思路,但是要注意一点,为了分层输出结果,我们需要每次都记录一下当前栈里面的节点个数,这个数目就是这一层节点的个数。每次出栈一层,然后进栈一层。

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
	vector<vector<int>> levelOrder(TreeNode* root) {
		vector<vector<int>>result;
		if (root == NULL)
			return result;
		vector<int>temp;
		queue<TreeNode*>record;
		record.push(root);
		
		while (record.size()!=0)
		{
			int size = record.size();
			while (size--)
			{
				TreeNode* tmp = record.front();
				record.pop();
				temp.push_back(tmp->val);
				if (tmp->left != NULL)
					record.push(tmp->left);
				if (tmp->right != NULL)
					record.push(tmp->right);
			}
			result.push_back(temp);
			temp.clear();
		
		}
		return result;
	}
};
发布了269 篇原创文章 · 获赞 3 · 访问量 8440

猜你喜欢

转载自blog.csdn.net/Xiao2018428/article/details/104716410