https://leetcode.com/problems/quad-tree-intersection/description/
我觉得是用意挺好的一题目。求两个四叉树的逻辑union,可惜测试用例里面居然包含对题目外因素的检查(那个id)懒得弄了。
思路其实挺简单,但是很容易忽略一个edge case,就是当所有children 的value 都一致时合并成整个leaf Node。
/* // Definition for a QuadTree node. class Node { public: bool val; bool isLeaf; Node* topLeft; Node* topRight; Node* bottomLeft; Node* bottomRight; Node() {} Node(bool _val, bool _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 == true) { return quadTree1; } else { return quadTree2; } } else if (quadTree2->isLeaf) { if (quadTree2->val == true) { return quadTree2; } else { return quadTree1; } } Node* topLeft = intersect(quadTree1->topLeft, quadTree2->topLeft); Node* topRight = intersect(quadTree1->topRight, quadTree2->topRight); Node* bottomLeft = intersect(quadTree1->bottomLeft, quadTree2->bottomLeft); Node* bottomRight = intersect(quadTree1->bottomRight, quadTree2->bottomRight); if (topLeft->isLeaf && topRight->isLeaf && bottomLeft->isLeaf && bottomRight->isLeaf) { if (topLeft->val == topRight->val == bottomLeft->val == bottomRight->val) { return new Node(topLeft->val, true, nullptr, nullptr, nullptr, nullptr); } } return new Node(0, false, topLeft, topRight, bottomLeft, bottomRight); } };