您的位置:首页 > 其它

LeetCode Binary Tree Level Order Traversal II

2014-11-05 21:29 253 查看
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.
题意:给出一个二叉树,按层次从高到低输出
思路:用BFS,先按层次从低到高,然后倒过来

/**
* 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) {
queue<TreeNode*> q;
vector<vector<int> > vv;
vector<int> v;

if (root) {
v.push_back(root->val);
vv.push_back(v);
}

q.push(root);
vector<TreeNode*> vt;
while (!q.empty()) {
TreeNode* cur = q.front(); q.pop();
vt.push_back(cur);
if (cur == NULL) continue;
q.push(cur->left);
q.push(cur->right);
}

int step = 2;
size_t j;

for (size_t i = 1; i < vt.size(); i = j) {
v.clear();

int cnt = 0;

for (j = i; j < i + step && j < vt.size(); j++) {
if (vt[j]) {
v.push_back(vt[j]->val);
cnt += 2;
}
}

step = cnt;
if (v.size() > 0) {
vv.push_back(v);
}
}

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