-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathancestorsInBinaryTree.cpp
More file actions
33 lines (32 loc) · 897 Bytes
/
ancestorsInBinaryTree.cpp
File metadata and controls
33 lines (32 loc) · 897 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
Structure of a node is as following
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
*/
class Solution {
public:
// logic - follow same logic as Lowest Common Ancestor
// Function should return all the ancestor of the target node
Node* ancestors(Node* root,int target,vector<int>&ans){
if(root==NULL) return NULL;
if(root->data==target) return root;
Node* left = ancestors(root->left,target,ans);
Node* right = ancestors(root->right,target,ans);
if(left==NULL&&right==NULL) return NULL;
if(left!=NULL||right!=NULL){
ans.push_back(root->data);
return root;
}
}
vector<int> Ancestors(struct Node *root, int target) {
// Code here
vector<int> ans;
if(root==NULL) return ans;
ancestors(root,target,ans);
return ans;
}
};