• 558. Quad Tree Intersection


    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);
        }
    };
  • 相关阅读:
    48. Rotate Image
    47. Permutations II
    46. Permutations
    45. Jump Game II
    44. Wildcard Matching
    43. Multiply Strings
    42. Trapping Rain Water
    41. First Missing Positive
    40. Combination Sum II
    39. Combination Sum
  • 原文地址:https://www.cnblogs.com/agentgamer/p/9770748.html
Copyright © 2020-2023  润新知