1 题目
给定一个二叉树,返回该二叉树由底层到顶层的层序遍历,(从左向右,从叶子节点到根节点,一层一层的遍历)
2 解法
2.1 我的最初解法
按照正常的层序遍历应该是从上到下的,只要用一个栈先临时存一下每一层的,在循环一遍:
/*** struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/class Solution {
public:/*** * @param root TreeNode类 * @return int整型vector<vector<>>*/vector<vector<int> > levelOrderBottom(TreeNode* root) {// write code herevector<vector<int>> res;if (root) {stack<vector<int>> tS;queue<TreeNode*> tQ;tQ.push(root);while (!tQ.empty()) {int queueSize = tQ.size();vector<int> tV;for (int i = 0; i < queueSize; i ++) {TreeNode* tmpNode = tQ.front();tQ.pop();tV.push_back(tmpNode->val);if (tmpNode->left)tQ.push(tmpNode->left);if (tmpNode->right)tQ.push(tmpNode->right);}tS.push(tV);}while (!tS.empty()) {vector<int> tV = tS.top();tS.pop();res.push_back(tV);}}return res;}
};