前言
刷题坚持每一天,以下题目引用自:力扣(LeetCode)
💎一、题目一
🏆1.题目描述
原题链接:link
二叉树上有 n 个节点,按从 0 到 n - 1 编号,其中节点 i 的两个子节点分别是 leftChild[i] 和 rightChild[i]。
只有 所有 节点能够形成且 只 形成 一颗 有效的二叉树时,返回 true;否则返回 false。
如果节点 i 没有左子节点,那么 leftChild[i] 就等于 -1。右子节点也符合该规则。
注意:节点没有值,本问题中仅仅使用节点编号。
示例 1:
输入:n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
输出:true
🏆2.解题思路
🔑思路:
每个节点值只出现一次,先找出根节点,根据连通性记录出现的节点值并统计个数,统计个数有
n
个节点返回真,否则返回假。
🏆3.代码详解
bool validateBinaryTreeNodes(int n, int* leftChild, int leftChildSize, int* rightChild, int rightChildSize){
int hash[n];
int idx = -1;
memset(hash, 0, sizeof(hash));
for(int i = 0; i < n; ++i){
if(leftChild[i] != -1){
++hash[leftChild[i]];
}
if(rightChild[i] != -1){
++hash[rightChild[i]];
}
}
for(int i = 0; i < n; ++i){
if(hash[i] == 0){
idx = i;
break;
}
}
if (idx == -1) return false;
int gether[n];
int queue[2*n];
int head = 0, tail = 0;
memset(gether, 0, sizeof(gether));
queue[tail++] = idx;
gether[idx] = 1;
while(head != tail){
int ret = queue[head++];
if(leftChild[ret] != -1){
if(gether[leftChild[ret]]) return false;
gether[leftChild[ret]] = 1;
queue[tail++] = leftChild[ret];
}
if(rightChild[ret] != -1){
if(gether[rightChild[ret]]) return false;
gether[rightChild[ret]] = 1;
queue[tail++] = rightChild[ret];
}
}
int count = 0;
for(int i = 0; i < n; ++i){
if(gether[i]) ++count;
}
return count == n;
}
💎二、题目二
🏆1.题目描述
原题链接:1367. 二叉树中的列表
给你一棵以 root 为根的二叉树和一个 head 为第一个节点的链表。
如果在二叉树中,存在一条一直向下的路径,且每个点的数值恰好一一对应以 head 为首的链表中每个节点的值,那么请你返回 True ,否则返回 False 。
一直向下的路径的意思是:从树中某个节点开始,一直连续向下的路径。
示例 1:
输入:head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
输出:true
解释:树中蓝色的节点构成了与链表对应的子路径。
🏆2.解题思路
🔑思路:
深搜,树的路径节点值和链表节点值依次比较。链表为空直接返回真,树为空直接返回假,节点值不同返回假。
🏆3.代码详解
bool dfs(struct ListNode* head, struct TreeNode* root){
if(head == NULL) return true;
if(root == NULL) return false;
if(head->val != root->val) return false;
return dfs(head->next, root->left) || dfs(head->next, root->right);
}
bool isSubPath(struct ListNode* head, struct TreeNode* root){
if(root == NULL) return false;
return dfs(head, root) || isSubPath(head, root->left) || isSubPath(head, root->right);
}
💎三、星球推荐
星球链接:英雄算法联盟
星球里有什么?
【朋友圈】一个极致精准的自律、编程、算法的小圈子。
【算法集训】以月为单位组织算法集训,每天四题,风雨无阻。
【排行榜】每天、每周都会有榜单,激励大家不断进步,不断成长。
【个人规划】每个人都写好自己的规划,也可以查看他人的规划,时刻警醒自己不掉队。
【打卡挑战】每日一题打卡、每日早起打卡、算法集训打卡、规划完成情况打卡。
在星球里做什么?
目前星球人数达到520+,在星球里你能够遇到一群志同道合之人,因为都是花钱进来的,你不会看到任何浑水摸鱼的人,每个人都有自己的每月规划,星主每月都会组织算法集训,每天一起刷题,你可以看到别人的解题报告,取其之长,补己之短。