您的位置:首页 > 其它

#70 Binary Tree Level Order Traversal II

2016-08-28 06:04 316 查看
题目描述:

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).

Have you met this question in a real interview? 

Yes

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]
]


题目思路:

这题和#71基本一样,只是在BFS之后,把得到的ans reverse一下即可(因为要求bottom to top).

Mycode(AC = 21ms):

/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/

class Solution {
/**
* @param root : The root of binary tree.
* @return : buttom-up level order a list of lists of integer
*/
public:
vector<vector<int>> levelOrderBottom(TreeNode *root) {
// write your code here
vector<vector<int>> ans;
if (root == NULL) return ans;

// initialize 2 queues, one to
// store tree nodes, one to store
// level/height of corresponding node
queue<TreeNode *> helper;
helper.push(root);
queue<int> levels;
levels.push(0);

while (!helper.empty()) {
TreeNode *node = helper.front();
helper.pop();

int level = levels.front();
levels.pop();

// push the node into ans, according
// to its level
if (ans.size() <= level) {
ans.push_back({node->val});
}
else {
ans[level].push_back(node->val);
}

// push the left/right tree and their
// corresponding level into queue
if (node->left) {
helper.push(node->left);
levels.push(level + 1);
}
if (node->right) {
helper.push(node->right);
levels.push(level + 1);
}
}

// reverse the final ans, because it requires bottom to top
reverse(ans.begin(), ans.end());
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息