【LeetCode】Binary Tree Level Order Traversal II
2014-09-23 21:26
405 查看
题目:
Binary Tree Level Order Traversal II
Total Accepted: 18664Total Submissions: 59503
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] ]
confused what
"{1,#,2,3}"means?
> read more on how binary tree is serialized on OJ.
分析:
其实就是二叉树的层次遍历,只是输出的时候自底向上,这个只需要使用一个栈就行了。
代码:
class Solution { public: vector<vector<int> > levelOrderBottom(TreeNode *root) { vector<vector<int> > ret; if (!root) { return ret; } int cnt = 0; int num = 1; stack<vector<int> > stk; queue<TreeNode*> q; q.push(root); stk.push(vector<int>()); while (!q.empty()) { TreeNode *cur = q.front(); q.pop(); stk.top().push_back(cur->val); if (cur->left) q.push(cur->left); if (cur->right) q.push(cur->right); if (++cnt == num && !q.empty()) { stk.push(vector<int>()); num = q.size(); cnt = 0; } } while (!stk.empty()) { ret.push_back(stk.top()); stk.pop(); } return ret; } };
相关文章推荐
- LeetCode-Binary Tree Level Order Traversal II
- 【LeetCode】-Binary Tree Level Order Traversal II
- LeetCode Binary Tree Level Order Traversal II
- 107[Leetcode].Binary Tree Level Order Traversal II
- 【LeetCode-面试算法经典-Java实现】【107-Binary Tree Level Order Traversal II(二叉树层序遍历II)】
- [leetcode]Binary Tree Level Order Traversal II @ Python
- [leetcode]Binary Tree Level Order Traversal II
- [leetcode]Binary Tree Level Order Traversal II
- [LeetCode 107] Binary Tree Level Order Traversal II
- LeetCode - Binary Tree Level Order Traversal II
- leetcode--Binary Tree Level Order Traversal II
- LeetCode107 Binary Tree Level Order Traversal II
- leetcode Binary Tree Level Order Traversal II
- LeetCode-Binary Tree Level Order Traversal II
- LeetCode_Binary Tree Level Order Traversal II
- leetcode~Binary Tree Level Order Traversal II
- LeetCode-Binary Tree Level Order Traversal II
- LeetCode - Binary Tree Level Order Traversal II
- LeetCode题解:Binary Tree Level Order Traversal II
- [Leetcode] Binary Tree Level Order Traversal II (Java)