给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
您在真实的面试中是否遇到过这个题?
Yes
哪家公司问你的这个题? LinkedIn Airbnb Amazon Cryptic Studios Dropbox Epic Systems TinyCo Hedvig Facebook Google Uber Yelp Apple Yahoo Bloomberg Zenefits Twitter Microsoft Snapchat
感谢您的反馈
样例
给一棵二叉树 {3,9,20,#,#,15,7}
:
3
/ \
9 20
/ \
15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/ class Solution {
public:
/*
* @param root: A Tree
* @return: Level order a list of lists of integer
*/
vector<vector<int>> levelOrder(TreeNode * root) {
// write your code here
queue<TreeNode*> q;
vector<vector<int>> ans;
if(root==NULL)
return ans;
int len;
q.push(root);
while(!q.empty())
{
len=q.size();
vector<int> res;
while(len--)
{
TreeNode *p=q.front();
q.pop();
res.push_back(p->val);
if(p->left)
q.push(p->left);
if(p->right)
q.push(p->right); }
ans.push_back(res);
}
return ans;
}
};