题目1509:树中两个结点的最低公共祖先
后续遍历即可,这样每次处理当前节点时,可以综合左右节点的信息进行处理。时间复杂度为O(n)
PS : 经查找维基百科LCA的定义,一个节点可以称为他自己的子节点。
注意:以下代码九度上第五个case没过
#include<iostream> using namespace std; struct Node{ int val; Node * left; Node * right; Node (int value){ val = value; left = NULL; right = NULL; } }; Node * createTree(){ int value; cin>>value; if(value == 0) return NULL; Node *root = new Node(value); root->left = createTree(); root->right = createTree(); return root; } void destroy(Node * root){ if(root == NULL) return ; Node * l = root->left; Node * r = root->right; delete root; destroy(l); destroy(r); } int findLCA(Node * root, int m1, int m2, int &value){ if(root == NULL || m1 == 0 || m2 == 0) return 0; int findleft = 0, findright = 0, mid = 0; findleft = findLCA(root->left, m1, m2, value); if(findleft < 2) findright = findLCA(root->right, m1, m2, value); if(root->val == m1 && root->val == m2) mid = 2; else if(root->val == m1 || root->val == m2) mid = 1; if(findleft == 1 && findright == 1 ){ value = root->val; return 2; } if((findleft == 1 || findright == 1) && mid == 1){ value = root->val; return 2; } if(mid == 2){ value = root->val; return 2; } return findleft | findright | mid; } int main(){ int n; int m1, m2, value; cin>>n; while(n--){ Node * root = createTree(); cin>>m1>>m2; value = 0; findLCA(root, m1, m2, value); if(value != 0) cout<<value<<endl; else cout<<"My God"<<endl; destroy(root); } return 0; }
ps 贴一个九度内部AC的代码 ,花了我20个九度豆买的,奶奶的
#include<stdio.h> #define N 10005 int tree[N][4],e; int find(int x){ int i; for(i=0;i<=e;i++) if(tree[i][3]==x) return i; return -1; } void build(int a) { int temp; scanf("%d",&temp); if(temp) { tree[a][1]=e; tree[e][3]=temp; tree[e][0]=a; e++; build(e-1); } scanf("%d",&temp); if(temp) { tree[a][2]=e; tree[e][3]=temp; tree[e][0]=a; e++; build(e-1); } } int main() { int n,i,m1,m2,s1,s2,t1,t2,c1,c2,c; while(scanf("%d",&n)!=EOF) { while(n--) { e=1; scanf("%d",&tree[0][3]); tree[0][0]=-1; build(0); scanf("%d %d",&m1,&m2); s1=s2=-1; s1=find(m1); s2=find(m2); if(s1!=-1&&s2!=-1) { t1=s1; t2=s2; c1=c2=0; while(tree[t1][0]!=-1) { c1++; t1=tree[t1][0]; } while(tree[t2][0]!=-1) { c2++; t2=tree[t2][0]; } if(c1>c2) { c=c1-c2; while(c--) s1=tree[s1][0]; } if(c2>c1) { c=c2-c1; while(c--) s2=tree[s2][0]; } while(s1!=s2) { s1=tree[s1][0]; s2=tree[s2][0]; } printf("%d\n",tree[s1][3]); } else printf("My God\n"); } } return 0; } /************************************************************** Problem: 1509 User: 282544883 Language: C Result: Accepted Time:90 ms Memory:1068 kb ****************************************************************/
--------------------------------------------------------------------天道酬勤!