Binary Tree Level Order Traversal
最后更新于:2022-04-01 22:56:41
**一. 题目描述**
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
~~~
**二. 题目分析**
无。
**三. 示例代码**
参考了Discussion中stellari的做法,递归进行层次遍历,并将每个level对应于相应的vector:
~~~
#include
#include
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) :val(x), left(NULL), right(NULL){}
};
class Solution
{
public:
vector > levelOrder(TreeNode *root)
{
vector > result;
orderTraversal(root, 1, result);
return result;
}
private:
void orderTraversal(TreeNode* root, int level, vector > & result)
{
if (root == NULL) return;
if (level > result.size()) // 每往下一级,创建一个空的vector保存该层数据
result.push_back(vector());
result[level - 1].push_back(root->val);
orderTraversal(root->left, level + 1, result);
orderTraversal(root->right, level + 1, result);
}
};
~~~
**四. 小结**
以上为递归实现,也可以写成迭代版本,时间复杂度O(n),空间复杂度O(1)。
';