使用广度优先遍历方法,使用队列。
/*** 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) {queue<TreeNode*> q;vector<vector<int>> res;if (root==NULL) return res;q.push(root);while(!q.empty()) {int size = q.size();vector<int> r;for (int i=0;i<size;++i) {TreeNode *current=q.front();q.pop();if (current->left!=NULL)q.push(current->left);if (current->right!=NULL)q.push(current->right);r.push_back(current->val);}res.push_back(r);}return res;}};
leedcode通过:
执行用时:4 ms, 在所有 C++ 提交中击败了70.70% 的用户内存消耗:12.1 MB, 在所有 C++ 提交中击败了85.29% 的用户
