Leecode 107
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
方法一:用栈的方法,先将当层入栈,取值,最后插入结果数组,每次插入到最前面,保证倒叙,最后插入的叶子再最前面。
代码:
std::vector<std::vector<int>> Leecode107_levelOrderBottom(TreeNode* root) {
std::vector<std::vector<int>> result;
if (root == NULL) return result;
std::queue<TreeNode*> q;
std::vector<int> tmp;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
if (q.front()->left != NULL)
q.push(q.front()->left);
if (q.front()->right != NULL)
q.push(q.front()->right);
tmp.push_back(q.front()->val);
q.pop();
}
result.insert(result.begin(), tmp);
tmp.resize(0);
}
return result;
}