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] ]
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
经典方法,用Queue的data structure,插入NULL的标志位。
/**
* Definition for binary tree
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > result;
if(root==NULL) return result;
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
vector<int> levelVal;
while(true)
{
TreeNode* cur = q.front();
q.pop();
if(cur==NULL)
{
result.push_back(levelVal);
levelVal.clear();
if(q.size()==0)
{
break;
}
else
{
q.push(NULL);
}
}
else
{
levelVal.push_back(cur->val);
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
}
return result;
}
};
本文介绍了一种经典的二叉树层次遍历算法,通过使用队列数据结构并插入NULL标志位来实现从左到右、按层遍历二叉树节点的值。通过实例展示了如何对给定的二叉树进行层次遍历,并返回每层节点值。
1552

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



