-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathL26_nodeToRootPathCpp
More file actions
36 lines (32 loc) · 938 Bytes
/
L26_nodeToRootPathCpp
File metadata and controls
36 lines (32 loc) · 938 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
34
35
36
bool getPath(TreeNode *root, vector<int> &arr, int x) {
// if root is NULL
// there is no path
if (!root)
return false;
// push the node's value in 'arr'
arr.push_back(root->val);
// if it is the required node
// return true
if (root->val == x)
return true;
// else check whether the required node lies
// in the left subtree or right subtree of
// the current node
if (getPath(root->left, arr, x) ||
getPath(root->right, arr, x))
return true;
// required node does not lie either in the
// left or right subtree of the current node
// Thus, remove current node's value from
// 'arr'and then return false
arr.pop_back();
return false;
}
vector<int> Solution::solve(TreeNode* A, int B) {
vector<int> arr;
if(A == NULL) {
return arr;
}
getPath(A, arr, B);
return arr;
}