当前位置:网站首页>LeetCode.558. 四叉树交集___分治
LeetCode.558. 四叉树交集___分治
2022-07-20 02:09:00 【向光.】
题目链接:
558. 四叉树交集
Solution:
- 主要在于理解好题意,其实就是一个递归问题,具体见代码注释。
Code:
/* // Definition for a QuadTree node. class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; public Node() {} public Node(boolean _val,boolean _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) { val = _val; isLeaf = _isLeaf; topLeft = _topLeft; topRight = _topRight; bottomLeft = _bottomLeft; bottomRight = _bottomRight; } }; */
/* 明确递归函数意义 */
class Solution {
public Node intersect(Node quadTree1, Node quadTree2) {
if(quadTree1.isLeaf){
if(quadTree1.val){
return new Node(true,true);
}
return new Node(quadTree2.val,quadTree2.isLeaf,quadTree2.topLeft,quadTree2.topRight,quadTree2.bottomLeft,quadTree2.bottomRight);
}
if(quadTree2.isLeaf){
if(quadTree2.val){
return new Node(true,true);
}
return new Node(quadTree1.val,quadTree1.isLeaf,quadTree1.topLeft,quadTree1.topRight,quadTree1.bottomLeft,quadTree1.bottomRight);
}
Node node1 = intersect(quadTree1.topLeft,quadTree2.topLeft);
Node node2 = intersect(quadTree1.topRight,quadTree2.topRight);
Node node3 = intersect(quadTree1.bottomLeft,quadTree2.bottomLeft);
Node node4 = intersect(quadTree1.bottomRight,quadTree2.bottomRight);
// 四个子节点的值要一样,且要保证他们均为叶子节点
// 因为原先是构建的时候,而构建其实就是造的节点都为新节点,即为子节点
if(node1.isLeaf && node2.isLeaf && node3.isLeaf && node4.isLeaf && node1.val == node2.val
&& node1.val == node3.val && node1.val == node4.val){
// 成功则代表其会融合为一个新的叶子节点
return new Node(node1.val,true);
}
return new Node(false,false,node1,node2,node3,node4);
}
}
边栏推荐
- 已解决No module named ‘flask_misaka‘【BUG解决】
- Introduction to audio and video -- Analysis of H.264 coding (macroblock + slice + frame)
- 数据库系统原理与应用教程(028)—— MySQL 的数据完整性(一):数据完整性概述
- 中职网络安全技能大赛P100-Web渗透测试
- 洛谷 P1873 [COCI 2011/2012 #5] EKO / 砍树 二分
- acwing 868. 筛质数
- 网络安全—综合渗透测试-CVE-2018-10933-libssh漏洞分析
- Xshell & putty color scheme
- Kubernetes Kube scheduler
- 力扣刷题61. 旋转链表
猜你喜欢
随机推荐
acwing 872. 最大公约数
Ppde Q2 welcome | welcome 22 AI developers to join the propeller developer technical expert program!
Is it difficult to develop a test platform?
The stock problem was wiped out
JSP自定义标签(一篇学会,每一行代码都有注释)
中職網絡安全—2022年國賽逆向PE Reverse解題思路
洛谷 P1678 烦恼的高考志愿
VMware安装
快速排序及优化
暑假安全第二次作业
The five safety links that are easy to be ignored are more dangerous than expected!
Network security in Secondary Vocational Schools - the thinking of reverse PE reverse problem solving in 2022 National Games
acwing 871. 约数之和
数据库系统原理与应用教程(027)—— MySQL 修改表中数据(三):改(update)
数据库系统原理与应用教程(031)—— MySQL 的数据完整性(四):定义外键(FOREIGN KEY)
NC | 全球变化背景下溶解有机碳和微生物的生态网络关系研究取得进展
配置双数据库
上次面试跪在了Redis上,刷完阿里表哥给的内部Redis文档,终面进大厂
Resolved no module named 'flask_ Misaka '[bug solution]
Baidu PaddlePaddle easydl helps manufacturing enterprises with intelligent transformation