文章目录
- 102. 二叉树的层序遍历
- 116. 填充每个节点的下一个右侧节点指针
- 199. 二叉树的右视图
- 111. 二叉树的最小深度
102. 二叉树的层序遍历
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
vector<vector<int>> ans;
if(root == nullptr){
return ans;
}
q.push(root);
while(!q.empty()){
int n = q.size();
vector<int> level;
for(int i = 0; i < n; i++){
TreeNode* node = q.front();
q.pop();
level.push_back(node->val);
if(nullptr != node->left){
q.push(node->left);
}
if(nullptr != node->right){
q.push(node->right);
}
}
ans.push_back(level);
}
return ans;
}
};
116. 填充每个节点的下一个右侧节点指针
除了每层最后一个节点不用处理,其他的节点都进行连接即可
class Solution {
public:
Node* connect(Node* root) {
if(root == nullptr){
return nullptr;
}
queue<Node*> q;
q.push(root);
while(!q.empty()){
int n = q.size();
for(int i = 0; i < n; i++){
Node* node = q.front();
q.pop();
if(i != n - 1){
node->next = q.front();
}
if(nullptr != node->left){
q.push(node->left);
}
if(nullptr != node->right){
q.push(node->right);
}
}
}
return root;
}
};
199. 二叉树的右视图
BFS:使用上面层序遍历的方式,保存每层最后一个节点的值即可
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
queue<TreeNode*> q;
vector<int> ans;
if(root == nullptr){
return ans;
}
q.push(root);
while(!q.empty()){
int n = q.size();
for(int i = 0; i < n; i++){
TreeNode* node = q.front();
q.pop();
if(i == n - 1){
ans.push_back(node->val);
}
if(nullptr != node->left){
q.push(node->left);
}
if(nullptr != node->right){
q.push(node->right);
}
}
}
return ans;
}
};
DFS:利用类似于先序遍历的VRL进行深度优先遍历,只存入每层第一个访问的节点,即最右侧的节点
class Solution {
public:
vector<int> ans;
void preorder(TreeNode* root, int depth){
if(root == nullptr){
return;
}
if(depth == ans.size()){
ans.push_back(root->val);
}
preorder(root->right, depth + 1);
preorder(root->left, depth + 1);
}
vector<int> rightSideView(TreeNode* root) {
preorder(root, 0);
return ans;
}
};
111. 二叉树的最小深度
用层序遍历的方式,从上往下遍历,一旦碰到叶子节点就可以返回当前深度了
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*> q;
int min_depth = 0;
if(root == nullptr){
return 0;
}
bool isExit = false;
q.push(root);
while(!q.empty()){
int n = q.size();
min_depth++;
for(int i = 0; i < n; i++){
TreeNode* node = q.front();
q.pop();
if(nullptr == node->left && nullptr == node->right){
isExit = true;
break;
}
if(nullptr != node->left){
q.push(node->left);
}
if(nullptr != node->right){
q.push(node->right);
}
}
if(isExit){
break;
}
}
return min_depth;
}
};
求最小深度和求最大深度不同,不能像求最大深度一样,节点为空就统一返回0,一个空节点返回了0,父节点向上返回时由于我们取左右孩子的最小值+1返回,此时父节点向上返回得永远是1
我们需要将不同的节点进行不同的递归,因此当节点一边空一边不空是,我们不对空子节点进行递归,防止上述情况出现
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == nullptr){
return 0;
}
if(nullptr == root->left && nullptr != root->right){
return minDepth(root->right) + 1;
}
if(nullptr != root->left && nullptr == root->right){
return minDepth(root->left) + 1;
}
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
};