问题:https://leetcode.com/problems/binary-tree-level-order-traversal-ii/?tab=Description
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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
分析:由于需要把每层的节点分别放入到数组中,因此需要引入变量n记录每层的节点数量。剩下的,就是广度优先搜索的方法了。广度优先搜索算法(Breadth First Search),又叫宽度优先搜索,或横向优先搜索。从根节点开始,沿着树的宽度遍历树的节点。如果所有节点均被访问,则算法中止。借助队列数据结构,由于队列是先进先出的顺序,因此可以先将左子树入队,然后再将右子树入队。这样一来,左子树结点就存在队头,可以先被访问到。
参考C++代码:
/**
* 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) {
vector<vector<int>> tt;
if(NULL==root) return tt;
queue<TreeNode *> q;
q.push(root);
while(!q.empty()){
vector<int> t;
int n=q.size();
for(int i=0;i<n;i++){
TreeNode* tem=q.front();
q.pop();
if(tem->left !=NULL){
q.push(tem->left);
}
if(tem->right !=NULL){
q.push(tem->right);
}
t.push_back(tem->val);
}
tt.push_back(t);
}
reverse(tt.begin(),tt.end());
return tt;
}
};