【Leetcode】—— 二叉树的层次遍历
程序员文章站
2022-06-07 10:49:07
...
一、leetcode102题 二叉树的层次遍历
1.1 题目描述
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
返回其层次遍历结果:
- [
- [3],
- [9,20],
- [15,7]
- ]
1.2 解题思路
1.3 代码实现
class Solution {
public:
void pre(TreeNode *root, int depth, vector<vector<int>> &ans) {
if (!root) return ;
if (depth >= ans.size())
ans.push_back(vector<int> {});
ans[depth].push_back(root->val);
pre(root->left, depth + 1, ans);
pre(root->right, depth + 1, ans);
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
pre(root, 0, ans);
return ans;
}
};
二、 leetcode107题 二叉树的层次遍历II
1.1 题目描述
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
1.2 解题思路
思路和102题思路一致,只是在得到遍历数组之后将该数组逆置之后返回即可,调用reverse,将vector数组迭代器区间传递给reverse即可逆置该数组。
1.3 代码实现
class Solution {
public:
void pre(TreeNode *root, int depth, vector<vector<int>> &ans) {
if (root == NULL) return ;
if (depth >= ans.size())
ans.push_back(vector<int> {});
ans[depth].push_back(root->val);
pre(root->left, depth + 1, ans);
pre(root->right, depth + 1, ans);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
pre(root, 0, ans);
reverse(ans.begin(), ans.end());
return ans;
}
};
上一篇: WPF自定义时间控件
下一篇: 转换器 IValueConverter