LCA树两个节点最低公共祖先
2016-01-24 17:40
363 查看
#include<iostream> #include<vector> using namespace std; struct Tree { Tree *pLeft; Tree *pRight; int nValue; }; bool FindPath(Tree *root,int nFindValue,vector<int> &vec) { if(root == NULL) { return false; } bool flag = false;//判断是否找到要找到的节点值(路径) vec.push_back(root->nValue); //将值放到vector中 if(root->nValue == nFindValue)//如果找到返回 true ,此时上一层的 flag 为true { return true; } if(!flag && root->pLeft != NULL)//如果找到值了,flag 为true 就不会继续查找了 { flag = FindPath(root->pLeft,nFindValue,vec); } if(!flag && root->pRight != NULL)//如果找到值了,flag 为true 就不会继续查找了 { flag = FindPath(root->pRight,nFindValue,vec); } if(flag == false)//如果找到值了 , 此时的路径 不应该 从 vector中 删除 { vec.pop_back(); } return flag; } int PanDuan(Tree *root,int nFindValue1,int nFindValue2) { vector<int> vec1,vec2; int nValue = -1; int flag1 = FindPath(root,nFindValue1,vec1); int flag2 = FindPath(root,nFindValue2,vec2); //////////////////////////////////////////////// for(int i=0;i<vec1.size();i++) { cout<<vec1[i]<<" "; } cout<<endl; for(int i=0;i<vec2.size();i++) { cout<<vec2[i]<<" "; } cout<<endl; //////////////////////////////////////////////// if(flag1 && flag2) { for(int i = 0 ; i< vec1.size()< vec2.size()?vec1.size():vec2.size();i++) { if(vec1[i] != vec2[i]) { break; } else { nValue = vec1[i]; } } } return nValue; } Tree *newNode(int nValue) { Tree *temp = new Tree; temp->nValue = nValue; temp->pLeft = NULL; temp->pRight = NULL; return temp; } int main() { Tree * root = newNode(1); root->pLeft = newNode(2); root->pRight = newNode(3); root->pLeft->pLeft = newNode(4); root->pLeft->pRight = newNode(5); root->pRight->pLeft = newNode(6); root->pRight->pRight = newNode(7); cout<<PanDuan(root,4,6)<<endl; return 0; }
相关文章推荐
- Activity与Service的交互一
- mybatis+log4j 打印sql
- JavaEE Tutorials (30) - Duke综合案例研究示例
- float 浮点数的无效值和无限大和无限小
- 树的打印方式
- 【转】Hadoop生态上几个技术的关系与区别:hive、pig、hbase 关系与区别
- hdu 1159(DP+字符串最长公共序列)
- iOS9 中不支持http
- Ceph安装
- HDOJ 2041 超级楼梯
- Hive简介
- JavaEE Tutorials (29) - Duke辅导案例研究示例
- tornado的简单使用
- 数据结构实现之索引优先队列用例(多路归并)
- uva 101 - The Blocks Problem
- JavaEE Tutorials (28) - Duke书店案例研究示例
- 监听短信数据库,获取验证码
- iTerm2 快捷键
- 如风一样,飞翔------Day37
- JavaEE Tutorials (27) - Java EE的并发工具