一.问题描述
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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[ [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<int> curr;
vector<vector<int>> res;
queue<TreeNode *> trace;
if(!root) return res;
trace.push(root);
while(!trace.empty()){
vector<int> curr_layer;
int len=trace.size();
for(int i=0;i<len;i++){
TreeNode* tmp = trace.front();
trace.pop();
if(!tmp) continue;
curr_layer.push_back(tmp->val);
trace.push(tmp->left);
trace.push(tmp->right);
}
if(curr_layer.size())
res.push_back(curr_layer);
}
return res;
}
};
本文介绍了一种解决二叉树层次遍历问题的方法。利用队列数据结构进行广度优先搜索,从根节点开始逐层遍历并返回每层节点的值。示例代码清晰展示了如何实现这一算法。
731

被折叠的 条评论
为什么被折叠?



