https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
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).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
代码:
/**
* 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> > ans;
if(!root) return ans;
level(root, ans, 1);
for(int i = 0; i < ans.size() / 2; i ++)
swap(ans[i], ans[ans.size() - 1 - i]);
return ans;
}
void level(TreeNode* root, vector<vector<int> >& ans, int depth) {
vector<int> v;
if(depth > ans.size()) {
ans.push_back(v);
v.clear();
}
ans[depth - 1].push_back(root -> val);
if(root -> left)
level(root -> left, ans, depth + 1);
if(root -> right)
level(root -> right, ans, depth + 1);
}
};
和之前的一个差不多 层序遍历然后把数组反过来可以了 是 Tree 的第 $20$ 题