【Lowest Common Ancestor of a Binary Search Tree】cpp
2015-07-14 12:35
507 查看
题目:
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
For example, the lowest common ancestor (LCA) of nodes
代码:
tips:
由于BST是数据有序的,因此找公共祖先要容易一些。
参考:http://bookshadow.com/weblog/2015/07/11/leetcode-lowest-common-ancestor-binary-search-tree/
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes
2and
8is
6. Another example is LCA of nodes
2and
4is
2, since a node can be a descendant of itself according to the LCA definition.
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if ( !root ) return NULL; if ( p->val>q->val ) swap(p, q); if ( root->val>=p->val && root->val<=q->val ) { return root; } else if ( root->val < p->val ) { return Solution::lowestCommonAncestor(root->right, p, q); } else { return Solution::lowestCommonAncestor(root->left, p, q); } } };
tips:
由于BST是数据有序的,因此找公共祖先要容易一些。
参考:http://bookshadow.com/weblog/2015/07/11/leetcode-lowest-common-ancestor-binary-search-tree/
相关文章推荐
- xcode项目编译C/C++文件could not build module foundation
- C++多线程编程时的数据保护
- 《Effective C++》——条款08:别让异常逃离析构函数
- C++程序中启动线程的方法
- 在Visual Studio使用C++开发Metro应用
- 运行C++11代码
- C++ 返回值为引用
- C++用opengl直接调用box2D 的debug绘图
- C++ 返回值为引用
- PHP调用C++扩展时memset/sizeof函数无效的问题
- 探究在C++程序并发时保护共享数据的问题
- C++中关于委派(Delegates)的实现示例
- C++实现当前时间动态显示的方法
- 内存映射文件详解-----C++实现(即一块内存和一个文件相映射对应)
- vs2010下C++调用lib或dll文件
- 转载并学习 C语言 sizeof函数详解
- AVL树C++实现
- CRT,C++运行时库详解(历史脉络以及相关名称定义和区别)
- [C++设计模式] strategy 策略模式
- C++中引用(&)的用法和应用实例 - blue—— - 博客园