【每日刷题】Day61
🥕个人主页:开敲🍉
🔥所属专栏:每日刷题🍍
🌼文章目录🌼
1. 671. 二叉树中第二小的节点 - 力扣(LeetCode)
2. 2331. 计算布尔二叉树的值 - 力扣(LeetCode)
3. LCR 149. 彩灯装饰记录 I - 力扣(LeetCode)
1. 671. 二叉树中第二小的节点 - 力扣(LeetCode)
//思路:层序遍历+排序。
int compare(const void* a,const void* b)
{
return (*(int*)a-*(int*)b);
}
typedef struct listnode
{
struct TreeNode* val;
struct listnode* next;
}LN;
int findSecondMinimumValue(struct TreeNode* root)
{
//以下层序遍历代码
int arr[26] = {0};
int count = 0;
LN* phead = (LN*)malloc(sizeof(LN));
LN* ptail = phead;
LN* node = (LN*)malloc(sizeof(LN));
node->val = root;
node->next = NULL;
ptail->next = node;
ptail = ptail->next;
while(phead!=ptail)
{
struct TreeNode* tmp = phead->next->val;
phead = phead->next;
arr[count++] = tmp->val;
if(tmp->left)
{
LN* node = (LN*)malloc(sizeof(LN));
node->val = tmp->left;
node->next = NULL;
ptail->next = node;
ptail = ptail->next;
}
if(tmp->right)
{
LN* node = (LN*)malloc(sizeof(LN));
node->val = tmp->right;
node->next = NULL;
ptail->next = node;
ptail = ptail->next;
}
}
//以上
//以下排序+查找
qsort(arr,count,sizeof(int),compare);
int ans = -1;
for(int i = 1;i<count;i++)
{
if(arr[i]>arr[i-1])
{
ans = arr[i];
break;
}
}
return ans;
}
2. 2331. 计算布尔二叉树的值 - 力扣(LeetCode)
//思路:遍历二叉树,当遇到叶子结点时直接返回值,计算非叶子结点的值。
bool IsLeafNode(struct TreeNode* root)
{
return !root->left&&!root->right;
}
bool _evaluateTree(struct TreeNode* root)
{
if(IsLeafNode(root))//遇到叶子结点直接返回值
return root->val;
bool left = _evaluateTree(root->left);//因为叶子结点非0即1,因此就是非false即true,使用bool类型变量接收。
bool right = _evaluateTree(root->right);
if(root->val==2)
root->val = left|right;//计算每个非叶子结点的值
else
root->val = left&right;
return root->val;
}
bool evaluateTree(struct TreeNode* root)
{
return _evaluateTree(root);
}
3. LCR 149. 彩灯装饰记录 I - 力扣(LeetCode)
//思路:层序遍历。这里的思路是用链表实现层序遍历。
typedef struct listnode
{
struct TreeNode* val;
struct listnode* next;
}LN;
int* decorateRecord(struct TreeNode* root, int* returnSize)
{
int* ans = (int*)malloc(sizeof(int)*10001);
int count = 0;
LN* phead = (LN*)malloc(sizeof(LN));
LN* ptail = phead;
if(root)
{
LN* node = (LN*)malloc(sizeof(LN));
node->val = root;
node->next = NULL;
ptail->next = node;
ptail = ptail->next;
}
while(phead!=ptail)
{
struct TreeNode* tmp = phead->next->val;
phead = phead->next;
ans[count++] = tmp->val;
if(tmp->left)
{
LN* node = (LN*)malloc(sizeof(LN));
node->val = tmp->left;
node->next = NULL;
ptail->next = node;
ptail = ptail->next;
}
if(tmp->right)
{
LN* node = (LN*)malloc(sizeof(LN));
node->val = tmp->right;
node->next = NULL;
ptail->next = node;
ptail = ptail->next;
}
}
*returnSize = count;
return ans;
}