给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
一、思路
(一)逆转层序遍历
先使用层序遍历,得到层序遍历的结果,将结果逆转即可
C++代码:
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
queue<TreeNode *> list1,list2;
if (root == NULL)
return ans;
list1.push(root);
while (!list1.empty() || !list2.empty()) {
vector<int> temp;
while (!list1.empty()) {
TreeNode* node = list1.front();
list1.pop();
temp.push_back(node->val);
if (node->left)
list2.push(node->left);
if (node->right)
list2.push(node->right);
}
if (!temp.empty()) {
ans.push_back(temp);
temp.clear();
}
while (!list2.empty()) {
TreeNode* node = list2.front();
list2.pop();
temp.push_back(node->val);
if (node->left)
list1.push(node->left);
if (node->right)
list1.push(node->right);
}
if (!temp.empty())
ans.push_back(temp);
}
reverse(ans);
return ans;
}
void reverse(vector<vector<int>>& ans) {
int j = ans.size() - 1, i = 0;
while (i < j) {
vector<int> temp = ans[i];
ans[i] = ans[j];
ans[j] = temp;
i++;
j--;
}
}
};
执行效率: