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; } };