0%

binary-tree-level-order-traversal-ii

Binary Tree Level Order Traversal II – LeetCode 107

Problem

Description

Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 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>> levelOrderBottom(TreeNode* root) {
if(!root) return vector<vector<int>>();
queue<TreeNode *> q;
vector<vector<int>> result;
q.push(root);
while(!q.empty()){
int size = q.size();
vector<int> now;
for(int i = 0; i != size; ++i){
TreeNode *tmp = q.front(); q.pop();
now.push_back(tmp->val);
if(tmp->left) { q.push(tmp->left);}
if(tmp->right) {q.push(tmp->right);}
}
result.insert(result.begin(),now);
}
return result;
}
};

思路

因为要求一层一层的输出,于是只好用BFS写,时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$6$ ms,排名$53.42\%$

Better

思路

递归解,妙在每层之间对于res的处理,值得借鉴,时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$6$ ms,排名$53.42\%$

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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>> levelOrderBottom(TreeNode* root) {
vector<vector<int> > res;
levelorder(root, 0, res);
return vector<vector<int> > (res.rbegin(), res.rend());
}
void levelorder(TreeNode *root, int level, vector<vector<int> > &res) {
if (!root) return;
if (res.size() == level) res.push_back({});
res[level].push_back(root->val);
if (root->left) levelorder(root->left, level + 1, res);
if (root->right) levelorder(root->right, level + 1, res);
}
};