-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest2.cpp
More file actions
67 lines (47 loc) · 1.22 KB
/
test2.cpp
File metadata and controls
67 lines (47 loc) · 1.22 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <bits/stdc++.h>
using namespace std;
struct treeNode{
int val;
treeNode *left;
treeNode *right;
treeNode(int x): val(x), left(NULL), right(NULL){}
};
treeNode* buildTree(){
int num;
cin >> num;
if(!num){return nullptr;}
treeNode *root=new treeNode(num);
root->left=buildTree();
root->right=buildTree();
return root;
}
treeNode* findVal(treeNode *root,treeNode *target){
if(root==nullptr || target == nullptr || &root == &target){return nullptr;}
if(root->left==target||root->right==target){return root;}
treeNode *left_res=findVal(root->left,target);
if(left_res!=nullptr){return left_res;}
return findVal(root->right,target);
}
void getPreOrder(treeNode* root) {
if(root == nullptr) {
cout << 0 << " ";
return;
}
cout << root->val << " ";
getPreOrder(root->left);
getPreOrder(root->right);
}
int main(){
treeNode *root=buildTree();
int num,target;
cin>>num;
while(num){
cin>>target;
treeNode *Tar=new treeNode(target);
treeNode *res=findVal(root,Tar);
if(res==nullptr){cout<<"0"<<endl;}
else{cout<<res->val<<endl;}
num--;
}
return 0;
}