最近公共祖先

来源:互联网 发布:linux修改sftp端口号 编辑:程序博客网 时间:2024/06/06 07:41

打印路径

#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;}}}

0 0