|
| 1 | +// Source : https://leetcode.com/problems/cousins-in-binary-tree/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2019-04-30 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. |
| 8 | + * |
| 9 | + * Two nodes of a binary tree are cousins if they have the same depth, but have different parents. |
| 10 | + * |
| 11 | + * We are given the root of a binary tree with unique values, and the values x and y of two different |
| 12 | + * nodes in the tree. |
| 13 | + * |
| 14 | + * Return true if and only if the nodes corresponding to the values x and y are cousins. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * |
| 18 | + * Input: root = [1,2,3,4], x = 4, y = 3 |
| 19 | + * Output: false |
| 20 | + * |
| 21 | + * Example 2: |
| 22 | + * |
| 23 | + * Input: root = [1,2,3,null,4,null,5], x = 5, y = 4 |
| 24 | + * Output: true |
| 25 | + * |
| 26 | + * Example 3: |
| 27 | + * |
| 28 | + * Input: root = [1,2,3,null,4], x = 2, y = 3 |
| 29 | + * Output: false |
| 30 | + * |
| 31 | + * Note: |
| 32 | + * |
| 33 | + * The number of nodes in the tree will be between 2 and 100. |
| 34 | + * Each node has a unique integer value from 1 to 100. |
| 35 | + * |
| 36 | + ******************************************************************************************************/ |
| 37 | + |
| 38 | +/** |
| 39 | + * Definition for a binary tree node. |
| 40 | + * struct TreeNode { |
| 41 | + * int val; |
| 42 | + * TreeNode *left; |
| 43 | + * TreeNode *right; |
| 44 | + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
| 45 | + * }; |
| 46 | + */ |
| 47 | +class Solution { |
| 48 | +public: |
| 49 | + bool isCousins(TreeNode* root, int x, int y) { |
| 50 | + int dx=0, dy=0; |
| 51 | + TreeNode *px=root, *py=root; |
| 52 | + dx = DepthAndParent(root, px, 0, x); |
| 53 | + dy = DepthAndParent(root, py, 0, y); |
| 54 | + if (dx && dy){ |
| 55 | + return (dx == dy && px != py); |
| 56 | + } |
| 57 | + |
| 58 | + return false; |
| 59 | + |
| 60 | + } |
| 61 | + |
| 62 | + int DepthAndParent(TreeNode* root, TreeNode*& parent, int depth, int x) { |
| 63 | + if (!root) return 0; |
| 64 | + if ( root->val == x) return depth; |
| 65 | + |
| 66 | + int d=0; |
| 67 | + parent = root; |
| 68 | + if ( ( d = DepthAndParent(root->left, parent, depth+1, x)) > 0 ) return d; |
| 69 | + |
| 70 | + parent = root; |
| 71 | + if ( ( d = DepthAndParent(root->right, parent, depth+1, x)) > 0 ) return d; |
| 72 | + return 0; |
| 73 | + } |
| 74 | +}; |
0 commit comments