求二叉树中两个节点的最低公共祖先
2015-08-29 17:27
357 查看
// 找到根节点到目标节点的一条路径,如果存在的话,保存到path中
// 主方法
bool GetNodePath(BinaryTreeNode *pRoot, BinaryTreeNode *pNode, list<BinaryTreeNode *> &path) { if (pRoot == pNode) { path.push_back(pRoot); return true; } if (pRoot == NULL) return false; path.push_back(pRoot); bool found = false; found = GetNodePath(pRoot->lchild, pNode, path); if (!found) found = GetNodePath(pRoot->rchild, pNode, path); if (!found) path.pop_back(); return found; }
// 主方法
BinaryTreeNode * GetLastCommonParent(BinaryTreeNode *pRoot, BinaryTreeNode *pNode1, BinaryTreeNode *pNode2) { if (pRoot == NULL || pNode1 == NULL || pNode2 == NULL) return NULL; list<BinaryTreeNode *> path1; bool bResult1 = GetNodePath(pRoot, pNode1, path1); if (!bResult1) return NULL; list<BinaryTreeNode *> path2; bool bResult2 = GetNodePath(pRoot, pNode2, path2); if (!bResult2) return NULL; BinaryTreeNode *pLast = NULL; list<BinaryTreeNode *>::const_iterator iter1 = path1.begin(); list<BinaryTreeNode *>::const_iterator iter2 = path2.begin(); while (iter1 != path1.end() && iter2 != path2.end()) { if (*iter1 == *iter2) pLast = *iter1; else break; ++iter1; ++iter2; } return pLast; }
相关文章推荐
- Scala 深入浅出实战经典 第68讲:Scala并发编程原生线程Actor、Cass Class下的消息传递和偏函数实战解析
- 小而精,小而美的一款开源的迷你框架Underscore.js
- 编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。
- 循环-01. 求整数段和(15)
- POJ 3162 - Walking Race(树形DP)
- Windows 2003密码重置
- Java集合类详解
- 1235:统计同成绩学生人数
- C源码@数据结构与算法->DisjointSet
- Apache与Tomcat
- 安装go语言
- C 面试题选(一)
- 计算广告学介绍
- bzoj-1488 图的同构
- 实例详解机器学习如何解决问题 转
- python 类和对象的属性
- Xcode 常用
- linux驱动调试技术
- 1099 -- 温度转化
- 精通Hibernate——级联操纵对象