最近公共祖先
来源:互联网 发布: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
- 最近公共祖先LCA
- 最近公共祖先(LCA)
- 最近公共祖先
- Lca 最近公共祖先
- 【最近公共祖先】Tree
- LCA----最近公共祖先
- 最近公共祖先问题
- LCA (最近公共祖先)
- POJ1330(最近公共祖先)
- 最近公共祖先
- 最近公共祖先模版
- 最近公共祖先问题
- 最近公共祖先
- 最近公共祖先
- 最近公共祖先问题
- POJ1330最近公共祖先
- LCA最近公共祖先
- 最近公共祖先问题
- CCLight解析
- Android数据存储——SDcard
- uC/OS--II的时间管理
- shell syntax error near unexpected token
- 写一个函数,将字符串首尾空格去除,并且字符串之间的多个空格合并成一个。
- 最近公共祖先
- 关于wamp配置虚拟主机支持多站点的操作
- linux或mac系统下的端口转发
- 赋值运算符的重载
- SQLite Android数据库详解
- 黑马程序员--动态类型检测
- Servlet的异常处理机制
- 【五校联考2015 9.5】送你一棵线段树
- 搭建go开发环境时,出现GoSublime error: MarGo build failed的问题