Advertisement
Guest User

Cousins in Binary Tree

a guest
Apr 8th, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.74 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     struct TreeNode *left;
  6.  *     struct TreeNode *right;
  7.  * };
  8.  */
  9.  
  10. int p1, p2, d1, d2;
  11.  
  12. void findDepth(struct TreeNode* root, int x, int y, int p, int dp){
  13.     if(d1 > -1 && d2 > -1)
  14.         return;
  15.     if(!root)
  16.         return;
  17.     if(root->val == x){
  18.         p1 = p;
  19.         d1 = dp;
  20.     }
  21.    
  22.     if(root->val == y){
  23.         p2 = p;
  24.         d2 = dp;
  25.     }
  26.    
  27.     findDepth(root->left, x, y, root->val, dp + 1);
  28.     findDepth(root->right, x, y, root->val, dp + 1);
  29. }
  30.  
  31. bool isCousins(struct TreeNode* root, int x, int y){
  32.     p1 = p2 = d1 = d2 = -1;
  33.     findDepth(root, x, y, -1, 0);
  34.    
  35.     return (p1 != p2) && (d1 == d2);
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement