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
| #include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode* left, * right; }; TreeNode* CreateTree() { int k; cin >> k; if (k == 0) return NULL; TreeNode* root = new TreeNode; root->val = k; root->left = CreateTree(); root->right = CreateTree(); return root; }
void traversal(TreeNode* root, vector<int>path,int x,vector<int>&path1) { if (root == NULL) return; path.push_back(root->val); if (root->val == x) { path1 = path; } traversal(root->left, path, x,path1); traversal(root->right, path, x,path1); }
int main() { TreeNode* root = new TreeNode; root = CreateTree(); int T; cin >> T; for (int i = 0; i < T; i++) { int a, b; cin >> a >> b; vector<int>path; vector<int>path1, path2; traversal(root, path, a,path1); traversal(root, path, b,path2); int n = min(path1.size(), path2.size()); int j = 0; for (j = 0; j < n; j++) { if (path1[j] != path2[j]) break; } j--; int len1 = path1.size() - 1; int len2 = path2.size() - 1; int len = len1 + len2 - 2 * j; cout << len << endl; for (int t = len1; t >= j; t--) cout << path1[t] << " "; for (int t = j + 1; t <= len2; t++) cout << path2[t] << " "; cout << endl; } }
|