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], ]
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
這一題和
Binary tree level order traversal的區別在於,輸出結果是從下往上一層層的遍歷節點,有兩種小聰明的方法:一、在上一題的最后反轉res然后輸出;二、使用棧。得到每一層的節點后,不直接壓入res中,先存入棧中,然后利用棧先進后出的特點,再壓入res,實現反轉。這兩題關鍵的部分在於如何單獨得到每一層的節點。以下兩種方法的主體部分也可以用上一題中的方法一,其核心思想不變
方法一:最后反轉
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution 11 { 12 public: 13 vector<vector<int>> levelOrderBottom(TreeNode* root) 14 { 15 vector<vector<int>> res; 16 queue<TreeNode *> Q; 17 if(root) Q.push(root); 18 19 while( !Q.empty()) 20 { 21 int count=0; 22 int levCount=Q.size(); 23 vector<int> levNode; 24 25 while(count<levCount) 26 { 27 TreeNode *curNode=Q.front(); 28 Q.pop(); 29 levNode.push_back(curNode->val); 30 if(curNode->left) 31 Q.push(curNode->left); 32 if(curNode->right) 33 Q.push(curNode->right); 34 count++; 35 } 36 res.push_back(levNode); 37 } 38 reverse(res.begin(),res.end()); //在上一題的基礎上增加一行 39 return res; 40 } 41 };
方法二:利用棧
/** * 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) { vector<vector<int>> res; queue<TreeNode *> Q; if(root) Q.push(root); stack<vector<int>> stk; while( !Q.empty()) { int count=0; int levCount=Q.size(); vector<int> levNode; while(count<levCount) { TreeNode *curNode=Q.front(); Q.pop(); levNode.push_back(curNode->val); if(curNode->left) Q.push(curNode->left); if(curNode->right) Q.push(curNode->right); count++; } stk.push(levNode); //壓入棧 } while(!stk.empty()) //出棧 { res.push_back(stk.top()); stk.pop(); } return res; } };