Binary Tree Level Order Traversal II [LEETCODE]
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) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > result; if(NULL == root){ return result; } vector<TreeNode *> v1; vector<TreeNode *> v2; vector<int> line; v1.push_back(root); while(!v1.empty()){ line.clear(); for (int i = 0; i < v1.size(); i++){ line.push_back(v1[i]->val); if(v1[i]->left) v2.push_back(v1[i]->left); if(v1[i]->right) v2.push_back(v1[i]->right); } result.push_back(line); v1 = v2; v2.clear(); } //reverse result vector using a temp stack stack<vector<int> >s; for (int i = 0; i < result.size(); i++){ s.push(result[i]); } result.clear(); while(!s.empty()){ result.push_back(s.top()); s.pop(); } return result; } };
Just revers result vetor using a temp stack, nothing else, AC in one submission.

浙公网安备 33010602011771号