C++解法一:
复制代码
1 // Iterative
2 class Solution {
3 public:
4 vector<vector<int> > levelOrder(TreeNode *root) {
5 vector<vector<int> > res;
6 if (root == NULL) return res;
7
8 queue<TreeNode*> q;
9 q.push(root);
10 while (!q.empty()) {
11 vector<int> oneLevel;
12 int size = q.size();
13 for (int i = 0; i < size; ++i) {
14 TreeNode *node = q.front();
15 q.pop();
16 oneLevel.push_back(node->val);
17 if (node->left) q.push(node->left);
18 if (node->right) q.push(node->right);
19 }
20 res.push_back(oneLevel);
21 }
22 return res;
23 }
24 };
复制代码
下面我们来看递归的写法,核心就在于我们需要一个二维数组,和一个变量level,当level递归到上一层的个数时,我们新建一个空层,继续往里面加数字。
C++解法二:
复制代码
1 // Recursive
2 class Solution {
3 public:
4 vector<vector<int>> levelOrder(TreeNode* root) {
5 vector<vector<int> > res;
6 levelorder(root, 0, res);
7 return res;
8 }
9 void levelorder(TreeNode *root, int level, vector<vector<int> > &res) {
10 if (!root) return;
11 if (res.size() == level) res.push_back({});
12 res[level].push_back(root->val);
13 if (root->left) levelorder(root->left, level + 1, res);
14 if (root->right) levelorder(root->right, level + 1, res);
15 }
16 };
亚马逊测评 www.yisuping.com