LeetCode刷题——二叉树2
层序遍历
一层一层遍历二叉树,广度优先搜索。用队列保存节点,队列加入头节点,队列不为空则执行循环体。记录此刻队列的长度,进入另一个循环,长度为循环次数。用t记录当前队列头部元素,q.pop(),如果t->left 不为空,将t->left加入队列,如果t->right不为空,将t->right加入队列。
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 l=q.size();
vector<int> a;
for(int i=0;i<l;++i){
TreeNode* t=q.front();
t=q.front();
q.pop();
a.push_back(t->val);
if(t->left!=nullptr) q.push(t->left);
if(t->right!=nullptr) q.push(t->right);
}
ans.push_back(a);
}
return ans;
}
};
二叉树的层次遍历 II
- 题目链接.
- 题意:给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
- 思路:层序遍历,在for循环里用vector加入该层元素,while循环内加入每层元素,最后再反转一下。
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
queue<TreeNode* > q;
vector<vector<int>> ans;
if(root==nullptr) return ans;
q.push(root);
while(!q.empty()){
int l=q.size();
vector<int> a;
for(int i=0;i<l;++i){
TreeNode* t=q.front();
t=q.front();
q.pop();
a.push_back(t->val);
if(t->left!=nullptr) q.push(t->left);
if(t->right!=nullptr) q.push(t->right);
}
ans.push_back(a);
}
reverse(ans.begin(),ans.end());
return ans;
}
};
填充每个节点的下一个右侧节点指针
- 题目链接.
- 题意:填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
- 思路:层序遍历,在for循环里进行处理。判断当前节点是否为当前层最后一个节点,如果是,则将 next 指针设置为 NULL。如果不是指向队头元素。
class Solution {
public:
Node* connect(Node* root) {
queue<Node*> q;
if(root==nullptr) return root;
q.push(root);
while(!q.empty()){
int l=size(q);
int i=0;
while(i!=l){
Node* t=q.front();
i++;
q.pop();
if(t->left) q.push(t->left);
if(t->right) {
q.push(t->right);
}
if(i==l) t->next=nullptr;
else t->next=q.front();
}
}
return root;
}
};
二叉树的最大深度
- 题目链接.
- 题意:给定一个二叉树,找出其最大深度。
- 思路:层序遍历,层数就是最大深度。
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode*> q;
int ans=0;
if(root==nullptr) return ans;
q.push(root);
while(!q.empty()){
int l=size(q);
for(int i=0;i<l;++i){
TreeNode* t=q.front();
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
ans++;
}
return ans;
}
};
二叉树的最小深度
- 题目链接.
- 题意:给定一个二叉树,找出其最小深度。
- 思路:层序遍历,当遍历到某节点没有左右节点时的层数,就是二叉树的最小深度。
class Solution {
public:
int minDepth(TreeNode* root) {
int ans=0;
if(root==nullptr) return ans;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int l=size(q);
ans++;
for(int i=0;i<l;++i){
TreeNode* t=q.front();
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
if(!t->left&&!t->right) return ans;
}
}
return ans;
}
};