[LeetCode] Binary Tree Level Order Traversal II

发布时间:2016-12-9 0:09:57 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"[LeetCode] Binary Tree Level Order Traversal II",主要涉及到[LeetCode] Binary Tree Level Order Traversal II方面的内容,对于[LeetCode] Binary Tree Level Order Traversal II感兴趣的同学可以参考一下。

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], ] 跟前面那个没什么区别,你要顺序添加了做一个reverse也行。 /** * 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 if ( !root ) return vector<vector<int> >(); deque<vector<int> > ans; vector<int> level; queue<TreeNode* > Q; Q.push(root); int lsum=1; while(lsum) { level.clear(); int next=0; while(lsum--) { TreeNode* t=Q.front(); Q.pop(); level.push_back(t->val); if ( t->left ) { Q.push(t->left); next++; } if ( t->right) { Q.push(t->right); next++; } } ans.push_front(level); lsum=next; } return vector<vector<int> >(ans.begin(),ans.end()); } };

上一篇:Poj 1151 Atlantis - 线段树
下一篇:实用技巧:Linux操作系统Vim/Vi编程提速

相关文章

相关评论