http://ac.jobdu.com/problem.php?pid=1509

此题最直观的方法是两次DFS,分别找到这两个节点的path,然后遍历path1和path2做比较,找到最后一个共同的元素。这个普通的做法在:http://blog.csdn.net/thyftguhfyguj/article/details/9232901

但有个更好的办法能够一次DFS中找到,没有O(logN)的额外空间。参见:http://www.cnblogs.com/lyunyu/archive/2013/05/11/3073529.html

现在这段代码有一个用例没有过,应该是没有同时找到两个节点(比如只找到一个)。这样可以放两个是否找到a和b的bool,最后有用,但这样代码会复杂不少。过会再做。(http://www.cnblogs.com/remlostime/archive/2012/11/26/2788795.html)现在这段代码只适用于两个子节点都有的情况。

但事实上LCA是一个成熟的算法,参考:http://wenku.baidu.com/view/6918633343323968011c92f4.html 有空回来再研究(看了一下,那个好像是基于并查集的离线算法)。

如果是二叉排序树,则可利用左右大小的性质:http://www.cnblogs.com/lautsie/p/3269174.html

#include <cstdio>
#include <iostream>
using namespace std; struct Node{
int x;
struct Node *left;
struct Node *right;
}; void createTree(Node *&root){
int x;
scanf_s("%d",&x);
if(!x)
root = NULL;
else{
root = new Node;
root->x = x;
createTree(root->left);
createTree(root->right);
}
} Node* getCommonNode(Node *&root, int a, int b){
if (root == NULL) {
return NULL;
}
else if (root->x == a || root->x == b){
return root;
}
else {
Node* rl = getCommonNode(root->left, a, b);
Node* rr = getCommonNode(root->right, a, b);
if (rl != NULL && rr != NULL) return root;
else {
Node* res = (rl != NULL) ? rl : rr;
return res;
}
}
} void destory(Node *&root){
if(root){
destory(root->left);
destory(root->right);
delete root;
root = NULL;
}
} void print(Node *root){
if(root){
printf("%d ",root->x);
print(root->left);
print(root->right);
}
} int main()
{
int n,a,b;
while(scanf_s("%d",&n) != EOF){
while(n--){
Node *root;
createTree(root);
scanf_s("%d %d",&a,&b);
Node * res = getCommonNode(root, a, b);
if (res != NULL) {
printf("%d\n", res->x);
}
else {
printf("My God\n");
}
destory(root);
}
}
return 0;
}

  

最新文章

  1. web预设模块化
  2. 前端工程师技能之photoshop巧用系列第三篇——切图篇
  3. EL表达式显示数据取整问题
  4. Java命令行的执行参数
  5. PHP5与MySQL数据库操作
  6. 十八、Java基础--------IO流体系以及字符流
  7. windows核心编程---第五章 线程的基础
  8. IT行业工作6年回顾
  9. 常见面试第二题之什么是Context
  10. 高性能的分布式内存对象缓存系统Memcached
  11. 和我一起来了解SEO
  12. PHP-FPM + Nginx: 502错误
  13. poj 2318 TOYS (二分+叉积)
  14. UpdatePanel与$.function()同时使用问题
  15. WPF FindName()查找命名注册的元素
  16. Cordova CLI源码分析(四)——创建工程
  17. 网络地址到物理地址的映射(ARP)
  18. Handling Captcha | Webdriver
  19. java 类加载机制 阿里面试题
  20. Django中的Form表单验证

热门文章

  1. 不关闭seLinux解决vsftpd服务本地用户不能登录问题(500 OOPS: cannot change directory:/home/***
  2. SharePoint 学习记事(三)
  3. 判断手机还是PC浏览器
  4. jQuery 源码分析5: jQuery 基本静态方法(一)
  5. Java实战之04JavaWeb-06DBUtils
  6. IO流06_处理流
  7. Convert CString to TCHAR
  8. GZIP 头解析
  9. 顺序表 C++模板实现
  10. 扩展:gridview 空数据时显示表头