最近公共祖先
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; } } }
相关文章推荐
- C++设计模式--单例、策略模式
- 二者必须点击一个
- 忘记Oracle密码怎么办
- php表单输入验证
- RelativeLayout中两个控件怎么居中显示
- Servlet新特性:异步处理
- android日志工具类
- Intent意图 IntentFilter介绍
- POJ1247解题报告
- Uva 12504-Updating a Dictionary(STL, map)
- leetcode Remove Nth Node From End of List java编程学习(七)
- JavaScript中函数参数的值传递和引用传递
- 得知OpenCV研究报告指出系列(一)VS2010+OpenCV2.4.9环境配置
- UART的FIFO功能
- map 的遍历
- cocos2d js 使用 cocos studio 合图出现的黑线
- 导航栏修改透明度
- 一个对象null,gc后依然可以绝境求生
- Hadoop 工作原理
- Django 之 下载文件