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,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
/**
* Definition for binary tree
* 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;
if (root == NULL) {
return res;
}
vector<int> r;
r.push_back(root->val);
res.push_back(r);
vector<TreeNode *> path;
path.push_back(root);
int count = 1;
while (!path.empty()) {
auto p = path.front();
if (p->left) {
path.push_back(p->left);
}
if (p->right) {
path.push_back(p->right);
}
count --;
path.erase(path.begin());
if (count == 0) {
vector<int> tmp;
for (auto iter = path.begin(); iter != path.end(); iter ++) {
tmp.push_back((*iter)->val);
}
if (tmp.size()>0){
res.push_back(tmp);
}
count = path.size();
}
}
reverse(res.begin(),res.end());
return res;
}
};
本文介绍了一种算法,用于实现二叉树的层次遍历并以从叶节点到根节点的方式返回各层级节点值。该算法使用了迭代方式,并记录每一层的节点值。
1560

被折叠的 条评论
为什么被折叠?



