leetcode--Binary Tree Level Order Traversal II
1.题目描述
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 7return its bottom-up level order traversal as:[[15,7][9,20],[3],]OJ's Binary Tree Serialization:The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.Here's an example:1/ \2 3/4\5The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
2解法分析
分析题意可知,题目类似于层序遍历但是又不同于层序遍历,不同点主要有:
- 普通层序遍历一股脑的将结果输出,没有将结果分层,要实现分层务必要记住每一层的有效节点数,这个可以通过一个变量来记录,并且,有了某一层的节点数之后,下一层的节点数是可以通过树结构推算出来的,所以我们只需两个变量即可始终获得当前被我们处理层还剩多少节点没被处理,当前层处理完后下一层还有多少节点需要处理也已知了。
- 分层结果反向,这个很简单,直接对最后的结果逆序就好了。
于是有了下面的代码:
/**
* Definition for binary tree
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int>> result;
if(!root)return result;queue<TreeNode *>q;int num_curLayer=1;
int num_nextLayer=0;
q.push(root);vector<int>curVec;
while(!q.empty())
{curVec.clear();while(num_curLayer>0)
{TreeNode *cur = q.front();q.pop();num_curLayer--;curVec.push_back(cur->val);if(cur->left){q.push(cur->left);num_nextLayer++;}
if(cur->right){q.push(cur->right);num_nextLayer++;}
}result.push_back(curVec);num_curLayer=num_nextLayer;num_nextLayer=0;}std::reverse(result.begin(),result.end());return result;
}};
代码一次性AC,很高兴,因为时间代价也很低: