给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
队列,把每层的结点放入后进入循环输出。 /** * 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) { if(root == NULL) return {}; vector<vector<int> > res; queue<TreeNode *> q; q.push(root); while(!q.empty()){ vector<int> tmp; int length = q.size(); while(length){ TreeNode* cur = q.front(); int data = cur->val; q.pop(); tmp.push_back(data); if(cur->left) q.push(cur->left); if(cur->right) q.push(cur->right); length--; } res.push_back(tmp); } return res; } };通过时间: