Jathin

Untitled

Sep 28th, 2021
608
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Definition for binary tree
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10. TreeNode* parent;
  11. int find_height_NodeB(TreeNode* A, int B){
  12.     if(A == NULL)
  13.         return -1;
  14.     int dist = -1;
  15.     if((A->left && A->left->val == B) || (A->right && A->right->val == B)){
  16.         parent = A;
  17.     }
  18.     if(A->val == B ||
  19.        (dist=find_height_NodeB(A->left, B)) >= 0 ||
  20.        (dist=find_height_NodeB(A->right, B)) >=0){
  21.             return dist + 1;
  22.     }
  23.     return dist;
  24. }
  25.  
  26. vector<int> find_cousins(TreeNode* A, TreeNode* current_parent, int height, int current_height, vector<int> &res){
  27.     if(current_height == height && parent->val != current_parent->val){
  28.         res.push_back(A->val);
  29.     }
  30.     if(A->right){
  31.          find_cousins(A->right, A, height, current_height+1, res);
  32.     }
  33.     if(A->left){
  34.         find_cousins(A->left, A, height, current_height+1, res);
  35.     }
  36.     return res;
  37. }
  38. vector<int> Solution::solve(TreeNode* A, int B) {
  39.       int height = find_height_NodeB(A,B);
  40.       vector<int>ans;
  41.       return find_cousins(A, A, height, 0, ans);
  42. }
  43.  
RAW Paste Data