[LeetCode] Quad Tree Intersection 四叉樹相交
A quadtree is a tree data in which each internal node has exactly four children: topLeft
, topRight
, bottomLeft
and bottomRight
. Quad trees are often used to partition a two-dimensional space by recursively subdividing it into four quadrants or regions.
We want to store True/False information in our quad tree. The quad tree is used to represent a N * N
isLeaf
and val
. isLeaf
is true if and only if the node is a leaf node. The val
attribute for a leaf node contains the value of the region it represents.For example, below are two quad trees A and B:
A: +-------+-------+ T: true | | | F: false | T | T | | | | +-------+-------+ | | | | F | F | | | | +-------+-------+ topLeft: T topRight: T bottomLeft: F bottomRight: F B: +-------+---+---+ | | F | F | | T +---+---+ | | T | T | +-------+---+---+ | | | | T | F | | | | +-------+-------+ topLeft: T topRight: topLeft: F topRight: F bottomLeft: T bottomRight: T bottomLeft: T bottomRight: F
Your task is to implement a function that will take two quadtrees and return a quadtree that represents the logical OR (or union) of the two trees.
A: B: C (A or B): +-------+-------+ +-------+---+---+ +-------+-------+ | | | | | F | F | | | | | T | T | | T +---+---+ | T | T | | | | | | T | T | | | | +-------+-------+ +-------+---+---+ +-------+-------+ | | | | | | | | | | F | F | | T | F | | T | F | | | | | | | | | | +-------+-------+ +-------+-------+ +-------+-------+
Note:
- Both
A
andB
represent grids of sizeN * N
. N
is guaranteed to be a power of 2.- If you want to know more about the quad tree, you can refer to its wiki.
- The logic OR operation is defined as this: "A or B" is true if
A is true
, or ifB is true
, or ifboth A and B are true
.
這道題又是一道四叉樹的題,說是給了我們兩個四叉樹,然後讓我們將二棵樹相交形成了一棵四叉樹,相交的機制採用的是或,即每個自區域相‘或’,題目中給的例子很好的說明了一些相‘或’的原則,比如我們看A和B中的右上結點,我們發現A樹的右上結點已經是一個值為true的葉結點,而B的右上結點還是一個子樹,那麼此時不論子樹裡有啥內容,我們相交後的樹的右上結點應該跟A樹的右上結點保持一致,假如A樹的右上結點值是false的話,相‘或’起不到任何作用,那麼相交後的樹的右上結點應該跟B樹的右上結點保持一致。那麼我們可以歸納出,只有某一個結點是葉結點了,我們看其值,如果是true,則相交後的結點和此結點保持一致,否則跟另一個結點保持一致。比較麻煩的情況是當兩個結點都不是葉結點的情況,此時我們需要對相對應的四個子結點分別呼叫遞迴函式,呼叫之後還需要進行進一步處理,因為一旦四個子結點的值相同,且都是葉結點的話,那麼此時應該合併為一個大的葉結點,參見程式碼如下:
class Solution { public: Node* intersect(Node* quadTree1, Node* quadTree2) { if (quadTree1->isLeaf) return quadTree1->val ? quadTree1 : quadTree2; if (quadTree2->isLeaf) return quadTree2->val ? quadTree2 : quadTree1; Node *tl = intersect(quadTree1->topLeft, quadTree2->topLeft); Node *tr = intersect(quadTree1->topRight, quadTree2->topRight); Node *bl = intersect(quadTree1->bottomLeft, quadTree2->bottomLeft); Node *br = intersect(quadTree1->bottomRight, quadTree2->bottomRight); if (tl->val == tr->val && tl->val == bl->val && tl->val == br->val && tl->isLeaf && tr->isLeaf && bl->isLeaf && br->isLeaf) { return new Node(tl->val, true, NULL, NULL, NULL, NULL); } else { return new Node(false, false, tl, tr, bl, br); } } };
類似題目:
參考資料: