|
| 1 | +PROBLEM: |
| 2 | + |
| 3 | + |
| 4 | +In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1. |
| 5 | +Two nodes of a binary tree are cousins if they have the same depth, but have different parents. |
| 6 | +We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree. |
| 7 | +Return true if and only if the nodes corresponding to the values x and y are cousins. |
| 8 | + |
| 9 | +Example 1: |
| 10 | +Input: root = [1,2,3,4], x = 4, y = 3 |
| 11 | +Output: false |
| 12 | + |
| 13 | +Example 2: |
| 14 | +Input: root = [1,2,3,null,4,null,5], x = 5, y = 4 |
| 15 | +Output: true |
| 16 | + |
| 17 | +Example 3: |
| 18 | +Input: root = [1,2,3,null,4], x = 2, y = 3 |
| 19 | +Output: false |
| 20 | + |
| 21 | + |
| 22 | +Note: |
| 23 | + |
| 24 | +The number of nodes in the tree will be between 2 and 100. |
| 25 | +Each node has a unique integer value from 1 to 100. |
| 26 | + |
| 27 | + |
| 28 | +SOLUTION: |
| 29 | + |
| 30 | + |
| 31 | +class Solution { |
| 32 | +public: |
| 33 | + bool isCousins(TreeNode* root, int x, int y) { |
| 34 | + unordered_map<int,pair<int,int>> m; |
| 35 | + |
| 36 | + helper(root,0,-1,m); |
| 37 | + |
| 38 | + if(m[x].first == m[y].first && m[x].second != m[y].second) |
| 39 | + return true; |
| 40 | + else |
| 41 | + return false; |
| 42 | + } |
| 43 | + |
| 44 | + void helper(TreeNode* root,int depth,int parent,unordered_map<int,pair<int,int>>& m) |
| 45 | + { |
| 46 | + if(root==NULL) |
| 47 | + return ; |
| 48 | + |
| 49 | + m[root->val]={depth,parent}; |
| 50 | + |
| 51 | + helper(root->left,depth+1,root->val,m); |
| 52 | + helper(root->right,depth+1,root->val,m); |
| 53 | + |
| 54 | + } |
| 55 | +}; |
0 commit comments