面试题50 树中两个结点的最低公共祖先
2016-04-10 16:18
549 查看
bool GetNodePath(TreeNode *pRoot, TreeNode *pNode, list<TreeNode *>&path) { if (pRoot == pNode) return true; path.push_back(pRoot); bool found = false; vector<TreeNode *>::iterator i = pRoot->m_vChildren.begin(); while (!found && i < pRoot->m_vChildren.end()) { found = GetNodePath(*i, pNode, path); ++i; } if (!found) path.pop_back(); return found; } TreeNode *GetLastCommonNode(const list<TreeNode*>& path1, const list<TreeNode*>& path2) { list<TreeNode*>::const_iterator iterator1 = path1.begin(); list<TreeNode*>::const_iterator iterator2 = path2.begin(); TreeNode* pLast = NULL; while (iterator1 != path1.end() && iterator2 != path2.end()) { if (*iterator1 == *iterator2) pLast = *iterator1; iterator1++; iterator2++; } return pLast; } TreeNode* GetLastCommonParent(TreeNode* pRoot, TreeNode* pNode1, TreeNode* pNode2) { if (pRoot == NULL || pNode1 == NULL || pNode2 == NULL) return NULL; list<TreeNode*> path1; GetNodePath(pRoot, pNode1, path1); list<TreddNode*> path2; GetNodePath(pRoot, pNode1, pNode2); return GetLastCommonNode(path1, path2); }
相关文章推荐
- 程序员三年一跳,为什么越跳越好?
- 面试常见问题链接
- 一个合格的程序员应该读过哪些书
- 从校招时间谈大学求职准备
- 程序员修炼之道-书评
- 多线程中的状态转换以及常见的面试题
- 决胜九月:mysql面试必会基础(四)
- 华为实习面试总结
- what i will be关于职业的思考
- iOS面试知识点之内存管理
- 熬夜并不值得程序员炫耀
- 电面:给一个数组找出和为k的两个数
- 面试题之螺旋矩阵
- 经典sql面试题
- 常见面试之机器学习算法思想简单梳理
- 数据库部分面试题
- 对标腾讯职级系统的26个上升通道,你能看清自己的职场宿命吗?
- 前端面试题整理——HTML篇
- [置顶] Android开发,java开发程序员常见基础面试题,更换两个变量的值,java逻辑代码
- [置顶] Android开发,java开发程序员常见面试题,求100-200之间的质数,java逻辑代码