Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
层序遍历二叉树是典型的广度优先搜索BFS的应用,但是这里稍微复杂一点的是,我们要把各个层的数分开,存到一个二维向量里面,大体思路还是基本相同的,建立一个queue,然后先把根节点放进去,这时候找根节点的左右两个子节点,这时候去掉根节点,此时queue里的元素就是下一层的所有节点,用一个for循环遍历它们,然后存到一个一维向量里,遍历完之后再把这个一维向量存到二维向量里,以此类推,可以完成层序遍历。代码如下:
解法一:
class Solution { public: vector<vector<int> > levelOrder(TreeNode *root) { vector<vector<int> > res; if (root == NULL) return res; queue<TreeNode*> q; q.push(root); while (!q.empty()) { vector<int> oneLevel; int size = q.size(); for (int i = 0; i < size; ++i) { TreeNode *node = q.front(); q.pop(); oneLevel.push_back(node->val); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } res.push_back(oneLevel); } return res; } };
下面我们来看递归的写法,核心就在于我们需要一个二维数组,和一个变量level,当level递归到上一层的个数,我们新建一个空层,继续往里面加数字,参见代码如下:
解法二:
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int> > res; levelorder(root, 0, res); return res; } 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); } };
本文转自博客园Grandyang的博客,原文链接:[LeetCode] Binary Tree Level Order Traversal 二叉树层序遍历
,如需转载请自行联系原博主。