# LeetCode - 0993. Cousins in Binary Tree(DFS 版) ### 題目網址:https://leetcode.com/problems/cousins-in-binary-tree/ ###### tags: `LeetCode` `Easy` `圖論` `深度優先搜尋(Depth First Search)` ```cpp= /* -LeetCode format- Problem: 993. Cousins in Binary Tree Difficulty: Easy by Inversionpeter */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { int depths[105] = {}, parents[105] = {}, nowDepth = 0; void DFS(TreeNode *nowNode) { depths[nowNode->val] = nowDepth; ++nowDepth; if (nowNode->left) { parents[nowNode->left->val] = nowNode->val; DFS(nowNode->left); } if (nowNode->right) { parents[nowNode->right->val] = nowNode->val; DFS(nowNode->right); } --nowDepth; } public: bool isCousins(TreeNode* root, int x, int y) { DFS(root); return depths[x] == depths[y] && parents[x] != parents[y]; } }; ```