Binary Tree level Order traversal IITotal accepted:37829 Total submissions:122499my submissions QuestionSolution
Given a binary tree, return the bottom-up level order traversal of its nodes ' values. (ie, from the left-to-right, the level by level from the leaf to root).
For example:
Given binary Tree {3,9,20,#,#,15,7} ,
3 / 9 / 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.
Hide TagsTree Breadth-first SearchHas you met this question in a real interview? Yes No
Discuss
#include <iostream> #include <vector> #include <list> #include <stack>using namespace std;// Definition for binary treestruct TreeNode {int val; TreeNode *left; TreeNode *right; TreeNode (int x): Val (x), left (null), right (NULL) {}};/* uses a breadth-first search method, a layer-by-level search, a queue for the search, a node for each layer in the queue, and one output per layer, In turn, in the title request, a stack is added, which in turn shows the node data */vector<vector<int> > Levelorder (TreeNode *root) {vector< vector<int> > last_result;//final result stack<vector<int> > stack_result;//as intermediate result if (root==null) Return last_result;list<treenode*> temp;//do the calculated queue treenode* temp_node;//as the intermediate variable//int depth=1;int row_size=1;// Record the number of nodes in each layer Temp.push_back (root), while (!temp.empty ()) {vector<int> temp_result;//set an intermediate vectorwhile for each layer node ( row_size--) {Temp_node=temp.front (); Temp.pop_front (); Temp_result.push_back (temp_node->val); if (temp_node-> Left!=null)//The left subtree into the queue temp.push_back (temp_node->left), if (temp_node->right!=null)//The right subtree into the queue temp.push_back ( Temp_node->right);} Row_size=temp.sizE (); Stack_result.push (temp_result);//Stack The data of each layer}while (!stack_result.empty ())//finally press the element in the stack to reverse the output {Last_result.push_ Back (Stack_result.top ()); Stack_result.pop ();} return last_result;} int main () {}
leetcode_107 title--binary tree level Order traversal II (binary tree, breadth first search, queue, stack)