LeetCode 515 在每个树行中找最大值 2023.11.8
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> result;
if(root == NULL)
return result;
queue<TreeNode*> que;
que.push(root);
while (!que.empty())
{
//用优先级队列,能默认排序从大到小
priority_queue<int> vec;
int size = que.size();
while (size--)
{
TreeNode *temp = que.front();
que.pop();
vec.push(temp->val);
if(temp->left)
que.push(temp->left);
if(temp->right)
que.push(temp->right);
}
//将优先级队列top()最大值记录在答案中
result.push_back(vec.top());
}
return result;
}
};
LeetCode 116 117填充每个节点的下一个右侧节点指针、II 2023.11.8
class Solution {
public:
Node* connect(Node* root) {
if(root == NULL)
return root;
queue<Node*> que;
que.push(root);
while (!que.empty())
{
int size = que.size();
while (size--)
{
Node* temp = que.front();
que.pop();
if(temp->left)
que.push(temp->left);
if(temp->right)
que.push(temp->right);
//核心:判断size值,如果不为0,则next指向下一个元素,为零则指向空
if(size)
temp->next = que.front();
else
temp->next = NULL;
}
}
return root;
}
};
LeetCode 104 二叉树的最大深度 2023.11.8
class Solution {
public:
//后序递归遍历
// int getdepth(TreeNode* root)
// {
// if(root == NULL)
// return 0;
// int leftdepth = getdepth(root->left);
// int rightdepth = getdepth(root->right);
// return max(leftdepth, rightdepth) + 1;
// }
//前序递归
int result;
void getdepth(TreeNode* root, int depth)
{
result = depth > result ? depth : result;
if(root == NULL)
return;
if(root->left)
getdepth(root->left, 1+depth);
if(root->right)
getdepth(root->right, 1+depth);
}
int maxDepth(TreeNode* root) {
//层序遍历
// int num = 0;
// if(root == NULL)
// return num;
// queue<TreeNode*> que;
// que.push(root);
// while (!que.empty())
// {
// int size = que.size();
// while (size--)
// {
// TreeNode *temp = que.front();
// que.pop();
// if(temp->left)
// que.push(temp->left);
// if(temp->right)
// que.push(temp->right);
// }
// //核心:每遍历完一层,层数加1
// num++;
// }
// return num;
//后序递归遍历
// return getdepth(root);
//前序递归调用
result = 0;
if(root == NULL)
return result;
getdepth(root, 1);
return result;
}
};
LeetCode 111 二叉树的最小深度 2023.11.8
class Solution {
public:
//后序遍历
int getheight(TreeNode* root)
{
if(root == NULL)
return 0;
if(root->left != NULL && root->right == NULL)
return 1 + getheight(root->left);
else if(root->left == NULL && root->right != NULL)
return 1 + getheight(root->right);
else
return 1 + min(getheight(root->left), getheight(root->right));
}
int minDepth(TreeNode* root) {
//层次遍历
// int num = 0;
// if(root == NULL)
// return num;
// queue<TreeNode*> que;
// que.push(root);
// while (!que.empty())
// {
// int size = que.size();
// num++;
// while (size--)
// {
// TreeNode *temp = que.front();
// que.pop();
// //如果左右根都无则为叶子结点
// if(temp->left == NULL && temp->right == NULL)
// return num;
// if(temp->left)
// que.push(temp->left);
// if(temp->right)
// que.push(temp->right);
// }
// }
// return num;
//后序遍历
return getheight(root);
}
};