Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for binary tree
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
- * };
- */
- TreeNode* parent;
- int find_height_NodeB(TreeNode* A, int B){
- if(A == NULL)
- return -1;
- int dist = -1;
- if((A->left && A->left->val == B) || (A->right && A->right->val == B)){
- parent = A;
- }
- if(A->val == B ||
- (dist=find_height_NodeB(A->left, B)) >= 0 ||
- (dist=find_height_NodeB(A->right, B)) >=0){
- return dist + 1;
- }
- return dist;
- }
- vector<int> find_cousins(TreeNode* A, TreeNode* current_parent, int height, int current_height, vector<int> &res){
- if(current_height == height && parent->val != current_parent->val){
- res.push_back(A->val);
- }
- if(A->right){
- find_cousins(A->right, A, height, current_height+1, res);
- }
- if(A->left){
- find_cousins(A->left, A, height, current_height+1, res);
- }
- return res;
- }
- vector<int> Solution::solve(TreeNode* A, int B) {
- int height = find_height_NodeB(A,B);
- vector<int>ans;
- return find_cousins(A, A, height, 0, ans);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement