[LeetCode] Binary Tree Level Order Traversal II
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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. vector<vector<int>> ans; if(root == NULL) return ans; vector<TreeNode*> cur; vector<int> curVal; cur.push_back(root); curVal.push_back(root -> val); while(!cur.empty()) { vector<vector<int>>::iterator it = ans.begin(); ans.insert(it, curVal); vector<TreeNode*> tmp; vector<int> tmpVal; for(int i = 0;i < cur.size();i++) { if(cur[i] -> left != NULL) { tmp.push_back(cur[i] -> left); tmpVal.push_back(cur[i] -> left -> val); } if(cur[i] -> right != NULL) { tmp.push_back(cur[i] -> right); tmpVal.push_back(cur[i] -> right -> val); } } cur = tmp; curVal = tmpVal; } return ans; } };