二叉树的层次遍历用数组返回

二叉树的层次遍历
遍历结果每一层用数组保存

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<vector<int>> ans;
    if(!root) return NULL;
    queue<TreeNode*> q;
    q.push(root);
    while(!q.empty())
    {
       vector<int> temp;
       int len=q.size();
       for(int i=0;i!=len;i++)
       {
         TreeNode* t=q.front();
         temp.push_back(t->val);
         q.pop();
         if(q->left) q.push(q->left);
         if(q->right) q.push(q->right);
       }
       ans.push_back(temp);
    }
    return ans;
  }
}
发布了22 篇原创文章 · 获赞 1 · 访问量 351

猜你喜欢

转载自blog.csdn.net/weixin_43086349/article/details/104615691