给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)
样例
给出一棵二叉树 {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
按照从下往上的层次遍历为:
[ [15,7], [9,20], [3]]
解题思路:现用上题的方法顺序储存一下数组,建立一个新的向量,倒着插进去返回即可。
class Solution { /** * @param root : The root of binary tree. * @return : buttom-up level order a list of lists of integer */ public: vector<vector<int>>ans,rans; void f(){ for(int i=ans.size()-1;i>=0;i--)rans.push_back(ans[i]); }; vector<vector<int>> levelOrderBottom(TreeNode *root) { // write your code here if(root==NULL)return ans; queue<TreeNode *>tem[2]; tem[0].push(root); int i=0; while(!tem[0].empty()||!tem[1].empty()){ vector<int>t; while(!tem[i].empty()){ t.push_back(tem[i].front()->val); if(tem[i].front()->left!=NULL)tem[(i+1)%2].push(tem[i].front()->left); if(tem[i].front()->right!=NULL)tem[(i+1)%2].push(tem[i].front()->right); tem[i].pop(); } ans.push_back(t); i=(i+1)%2; } f(); return rans; } };