1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public: bool isCousins(TreeNode* root, int x, int y) { this->x = x; this->y = y; preorder(root, nullptr, y); return prex != prey && dx == dy; } private: int dx = -1; int dy = -1; int x; int y; TreeNode* prex; TreeNode* prey; void preorder(TreeNode* root, TreeNode* pre, int d) { if (root == nullptr) return; if (root->val == x) { prex = pre; dx = d; } if (root->val == y) { prey = pre; dy = d; } if (dx != -1 && dy != -1) return; preorder(root->left, root, d + 1); preorder(root->right, root, d + 1); } };
|