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] ]
思路:队列, 两个变量记录当前level的node数和下一个level的node数。
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 public: 12 vector<vector<int> > levelOrderBottom(TreeNode *root) { 13 14 vector<vector<int>> temp=levelOrder(root); 15 vector<vector<int>> res; 16 for(int i=temp.size()-1;i>=0;i--) 17 res.push_back(temp[i]); 18 return res; 19 } 20 21 vector<vector<int>> levelOrder(TreeNode* root) 22 { 23 vector<vector<int>> res; 24 if(root==NULL)return res; 25 queue<TreeNode*> s; 26 vector<int> level; 27 s.push(root); 28 int level_count=1;//important 29 int next_level_count=0;//important 30 while(!s.empty()) 31 { 32 TreeNode* root=s.front(); 33 s.pop(); 34 level_count--; 35 level.push_back(root->val); 36 37 if(root->left!=NULL){s.push(root->left);next_level_count++;} 38 if(root->right!=NULL){s.push(root->right);next_level_count++;} 39 40 if(level_count==0) 41 { 42 res.push_back(level); 43 level.clear(); 44 level_count=next_level_count; 45 next_level_count=0; 46 } 47 } 48 return res; 49 } 50 };
浙公网安备 33010602011771号