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] ]
思路:使用两个队列完成层次搜索,结果存储在vector中。
若使用一个队列,也可完成层次遍历,只是不清楚遍历到哪个层次了。两个队列可以知道目前元素所在的层次。
/** * Definition for a binary tree node. * 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) { result.clear(); if(!root) return result; vector<int> level; TreeNode * current; queue<TreeNode * > queToPop; queue<TreeNode * > queToPush; queToPop.push(root); while(!queToPop.empty()) { while(!queToPop.empty()) { current = queToPop.front(); queToPop.pop(); level.push_back(current->val); if(current->left) { queToPush.push(current->left); //若使用一个队列,这里应该是queToPop.push(...),只要queToPop不为空,就继续pop和push } if(current->right) { queToPush.push(current->right); } } result.push_back(level); level.clear(); swap(queToPop, queToPush); } reverse(result.begin(), result.end()); //逆序vector的方法 return result; } private: vector<vector<int>> result; };
时间: 2024-10-11 23:11:53