Binary tree? Traverse the level!
Title:
Given a binary tree, the node returns its bottom-up value hierarchy traversal. (Ie, by physical layer to the layer from the leaf nodes of the root node, layer by layer traversal from left to right)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
Topic analysis
- Goal: traverse the level from the bottom up +
Ideas
for each layer ==> Save this layer with a queue node
for a point in the queue ==> read node value + the child node in a queue
Problem-solving ideas
variable | effect |
---|---|
q | Save Node queue |
years | Save traverse the level of results |
process
Root node in the queue
When the queue is not empty
- For controlling the number of cycles for each layer by
- Reading the first node value
- The first node from the team
- Child node into the team
- End for loop ==> one traversed node inserted ans foremost
code show as below
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
if(!root) return {};
queue<TreeNode*> q{{root}};
vector<vector<int>> ans;
while(!q.empty())
{
vector<int> one;
for (int i = q.size(); i > 0; i--){ //控制一层的结点个数
TreeNode *t = q.front();
q.pop();
one.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
ans.insert(ans.begin(),one); //插入到结果最前面
}
return ans;
}
};