https://leetcode.com/problems/quad-tree-intersection/description/
我觉得是用意挺好的一题目。求两个四叉树的逻辑union,可惜测试用例里面居然包含对题目外因素的检查(那个id)懒得弄了。
思路其实挺简单,但是很容易忽略一个edge case,就是当所有children 的value 都一致时合并成整个leaf Node。
1/* 2// Definition for a QuadTree node. 3class Node { 4public: 5 bool val; 6 bool isLeaf; 7 Node* topLeft; 8 Node* topRight; 9 Node* bottomLeft; 10 Node* bottomRight; 11 12 Node() {} 13 14 Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) { 15 val = _val; 16 isLeaf = _isLeaf; 17 topLeft = _topLeft; 18 topRight = _topRight; 19 bottomLeft = _bottomLeft; 20 bottomRight = _bottomRight; 21 } 22}; 23*/ 24class Solution { 25public: 26 Node* intersect(Node* quadTree1, Node* quadTree2) { 27 if (quadTree1->isLeaf) { 28 if (quadTree1->val == true) { 29 return quadTree1; 30 } else { 31 return quadTree2; 32 } 33 } 34 else if (quadTree2->isLeaf) { 35 if (quadTree2->val == true) { 36 return quadTree2; 37 } else { 38 return quadTree1; 39 } 40 } 41 42 Node* topLeft = intersect(quadTree1->topLeft, quadTree2->topLeft); 43 Node* topRight = intersect(quadTree1->topRight, quadTree2->topRight); 44 Node* bottomLeft = intersect(quadTree1->bottomLeft, quadTree2->bottomLeft); 45 Node* bottomRight = intersect(quadTree1->bottomRight, quadTree2->bottomRight); 46 47 if (topLeft->isLeaf && topRight->isLeaf && bottomLeft->isLeaf && bottomRight->isLeaf) { 48 if (topLeft->val == topRight->val == bottomLeft->val == bottomRight->val) { 49 return new Node(topLeft->val, true, nullptr, nullptr, nullptr, nullptr); 50 } 51 } 52 return new Node(0, false, topLeft, topRight, bottomLeft, bottomRight); 53 } 54};