您的位置:首页 > 其它

【LeetCode】Binary Tree Level Order Traversal II

2014-09-23 21:26 381 查看

题目:

Binary Tree Level Order Traversal II

Total Accepted: 18664
Total 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;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: