您的位置:首页 > 其它

最近公共祖先

2015-09-08 18:26 417 查看
打印路径

#include<stdio.h>
#include<string.h>
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;

struct TreeNode
{
int val;
TreeNode *left,*right;
};

TreeNode* createTree()
{
int val;
scanf("%d",&val);
if(val==0) return NULL;
TreeNode *root=new TreeNode;
root->val=val;
root->left=createTree();
root->right=createTree();
return root;
}

int flag;
void dfs(TreeNode *root,int target,vector<TreeNode*> &path)
{
if(flag==1)return;
if(root==NULL)return;
if(root->val==target)
{
flag=1;
path.push_back(root);
return;
}
path.push_back(root);
dfs(root->left,target,path);
dfs(root->right,target,path);
if(!flag)
path.pop_back();
}
TreeNode* findNode(vector<TreeNode*> path1,vector<TreeNode*> path2)
{
if(path1.size()==0||path2.size()==0)return NULL;
int len1=path1.size(),len2=path2.size();
int i=0;
while(i<len1&&i<len2)
{
if(path1[i]->val!=path2[i]->val)break;
i++;
}
return path1[i-1];
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
TreeNode *root = createTree();
int tar1,tar2;
scanf("%d%d",&tar1,&tar2);
vector<TreeNode*> path1;
vector<TreeNode*> path2;
flag=0;
dfs(root,tar1,path1);
flag=0;
dfs(root,tar2,path2);
for(int i=0;i<path1.size();i++)
{
printf("%d ",path1[i]->val);
}
puts("");
for(int i=0;i<path2.size();i++)
{
printf("%d ",path2[i]->val);
}
puts("");
TreeNode *res = findNode(path1,path2);
if(res == NULL)
{
cout<<"My God"<<endl;
}
else
{
cout<<res->val<<endl;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: