1143 Lowest Common Ancestor(30 分)【最近公共祖先】
阿新 • • 發佈:2019-02-13
二叉搜尋樹的建樹和尋找最近公共祖先(題目給出了BST的前序遍歷,而前序遍歷升序排列就是BST的中序遍歷了)
#include <bits/stdc++.h> using namespace std; typedef struct node *Node; typedef struct node{ int val; Node l,r; }node; Node T; int M,N; int pre[10001]; Node buildTree(int s,int e) { if(e < s) return NULL; if(s == e){ Node tnode = (Node)malloc(sizeof(node)); tnode->val = pre[s]; tnode->l = NULL; tnode->r = NULL; return tnode; } int i = s+1; while(i<=e && pre[i]<pre[s]) i++; Node tnode = (Node)malloc(sizeof(node)); tnode->val = pre[s]; tnode->l = buildTree(s+1,i-1); tnode->r = buildTree(i,e); return tnode; } bool findd(Node tree, int a, int b,int f) { if(f == 0){ if(tree == NULL){ printf("ERROR: %d and %d are not found.\n", a, b); return true; } if(a<tree->val && b<tree->val)return findd(tree->l,a,b,0); else if(a>tree->val && b>tree->val) return findd(tree->r,a,b,0); else{ bool fda = tree->val == a || findd(tree->l,a,0,1) || findd(tree->r,a,0,1); bool fdb = tree->val == b || findd(tree->l,b,0,1) || findd(tree->r,b,0,1); if(fda&&fdb){ if(tree->val == a||tree->val == b) printf("%d is an ancestor of %d.\n", tree->val == a ? a : b, tree->val == b ? a : b); else printf("LCA of %d and %d is %d.\n", a, b, tree->val); } else if (fda == false && fdb == false) { printf("ERROR: %d and %d are not found.\n", a, b); } else { printf("ERROR: %d is not found.\n", fda ? b : a); } return true; } } else{ if(tree == NULL) return false; if(tree->val == a) return true; if(tree->val > a)return findd(tree->l,a,0,1); return findd(tree->r,a,0,1); } } int main() { cin>>M>>N; int a,b; for(int i=0;i<N;i++){ cin>>pre[i]; } T = buildTree(0,N-1); for(int i=0;i<M;i++){ cin>>a>>b; findd(T, a, b, 0); } return 0; }
看到有一種非常巧妙的方法,都不需要建樹:
map<int, bool> mp用來標記樹中所有出現過的結點,遍歷一遍pre陣列,將當前結點標記為a,如果u和v分別在a的左、右,或者u、v其中一個就是當前a,即(a >= u && a <= v) || (a >= v && a <= u),說明找到了這個共同最低祖先a,退出當前迴圈,最後根據要求輸出結果即可
#include <iostream> #include <vector> #include <map> using namespace std; map<int, bool> mp; int main() { int m, n, u, v, a; scanf("%d %d", &m, &n); vector<int> pre(n); for (int i = 0; i < n; i++) { scanf("%d", &pre[i]); mp[pre[i]] = true; } for (int i = 0; i < m; i++) { scanf("%d %d", &u, &v); for(int j = 0; j < n; j++) { a = pre[j]; if ((a >= u && a <= v) || (a >= v && a <= u)) break; } if (mp[u] == false && mp[v] == false) printf("ERROR: %d and %d are not found.\n", u, v); else if (mp[u] == false || mp[v] == false) printf("ERROR: %d is not found.\n", mp[u] == false ? u : v); else if (a == u || a == v) printf("%d is an ancestor of %d.\n", a, a == u ? v : u); else printf("LCA of %d and %d is %d.\n", u, v, a); } return 0; }