|
| 1 | + |
| 2 | + |
| 3 | + |
| 4 | + |
| 5 | +/* |
| 6 | +// Definition for a QuadTree node. |
| 7 | +class Node { |
| 8 | +public boolean val; |
| 9 | +public boolean isLeaf; |
| 10 | +public Node topLeft; |
| 11 | +public Node topRight; |
| 12 | +public Node bottomLeft; |
| 13 | +public Node bottomRight; |
| 14 | +
|
| 15 | +public Node() {} |
| 16 | +
|
| 17 | +public Node(boolean _val,boolean _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) { |
| 18 | +val = _val; |
| 19 | +isLeaf = _isLeaf; |
| 20 | +topLeft = _topLeft; |
| 21 | +topRight = _topRight; |
| 22 | +bottomLeft = _bottomLeft; |
| 23 | +bottomRight = _bottomRight; |
| 24 | +} |
| 25 | +}; |
| 26 | +*/ |
| 27 | + |
| 28 | +public class QuadTreeIntersection558 { |
| 29 | +public Node intersect(Node quadTree1, Node quadTree2) { |
| 30 | +if (quadTree1 == null || quadTree2 == null) { |
| 31 | +return null; |
| 32 | +} |
| 33 | + |
| 34 | +Node res = new Node(); |
| 35 | +if (quadTree1.isLeaf && quadTree2.isLeaf) { |
| 36 | +res.isLeaf = true; |
| 37 | +res.val = quadTree1.val || quadTree2.val; |
| 38 | +return res; |
| 39 | +} |
| 40 | + |
| 41 | +res.topLeft = intersect(getTopLeft(quadTree1), getTopLeft(quadTree2)); |
| 42 | +res.topRight = intersect(getTopRight(quadTree1), getTopRight(quadTree2)); |
| 43 | +res.bottomLeft = intersect(getBottomLeft(quadTree1), getBottomLeft(quadTree2)); |
| 44 | +res.bottomRight = intersect(getBottomRight(quadTree1), getBottomRight(quadTree2)); |
| 45 | + |
| 46 | +if (allLeaves(res) && allSame(res)) { |
| 47 | +res.isLeaf = true; |
| 48 | +res.val = res.topLeft.val; |
| 49 | +return res; |
| 50 | +} |
| 51 | +return res; |
| 52 | +} |
| 53 | + |
| 54 | +private Node getTopLeft(Node n) { |
| 55 | +return n.isLeaf ? n : n.topLeft; |
| 56 | +} |
| 57 | + |
| 58 | +private Node getTopRight(Node n) { |
| 59 | +return n.isLeaf ? n : n.topRight; |
| 60 | +} |
| 61 | + |
| 62 | +private Node getBottomLeft(Node n) { |
| 63 | +return n.isLeaf ? n : n.bottomLeft; |
| 64 | +} |
| 65 | + |
| 66 | +private Node getBottomRight(Node n) { |
| 67 | +return n.isLeaf ? n : n.bottomRight; |
| 68 | +} |
| 69 | + |
| 70 | +private boolean allLeaves(Node n) { |
| 71 | +return n.topLeft.isLeaf && |
| 72 | +n.topRight.isLeaf && |
| 73 | +n.bottomLeft.isLeaf && |
| 74 | +n.bottomRight.isLeaf; |
| 75 | +} |
| 76 | + |
| 77 | +private boolean allSame(Node n) { |
| 78 | +return (n.topLeft.val == n.topRight.val) && |
| 79 | +(n.bottomLeft.val && n.bottomRight.val) && |
| 80 | +(n.topLeft.val && n.bottomLeft.val); |
| 81 | +} |
| 82 | + |
| 83 | +} |
| 84 | + |
0 commit comments