LCA树两个节点最低公共祖先
来源:互联网 发布:c一维数组排序算法 编辑:程序博客网 时间:2024/05/21 07:38
#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;}
1 0
- LCA树两个节点最低公共祖先
- 寻找二叉树两个节点的最低公共祖先(LCA)
- 树——树中两个节点的最低公共祖先LCA
- 树——在二叉树中找到两个节点的最低公共祖先LCA
- 面试题50 树中两个节点的最低公共祖先LCA(Lowest Common Ancestor )
- 最低公共祖先LCA
- 树中两个节点的最低公共祖先
- 树中两个节点的最低公共祖先
- 找出树中两个节点的最低公共祖先
- 二叉树中查找两个节点的最低公共祖先
- 树中两个节点的最低公共祖先
- 树的两个节点的最低公共祖先
- 剑指offer-树中两个节点的最低公共祖先
- 求二叉树中两个节点的最低公共祖先
- 寻找二叉树两个节点的最低公共祖先
- 寻找二叉树两个节点的最低公共祖先
- 寻找二叉树两个节点的最低公共祖先
- 二叉树中两个节点的最低公共祖先
- Ceph安装
- HDOJ 2041 超级楼梯
- 使用struts2+spring+hibernate测试多对多关系映射的时候出现懒加载问题:could not initialize proxy - no Session
- 树的打印方式
- mybatis+log4j 打印sql
- LCA树两个节点最低公共祖先
- Activity与Service的交互一
- Partial Class verse Partial Method
- (模拟) uva 1589 Xiangqi
- linux macro time_after学习
- floyd判圈算法 (UVA 11549 - Calculator Conundrum)
- 二叉搜索树的后序遍历序列序列判断是否是二叉搜索树
- 80. Binary Tree Paths
- 文件系统