235——Lowest Common Ancestor of a Binary Search Tree(二叉排序树)
2015-07-19 11:09
357 查看
Lowest Common Ancestor of a Binary Search Tree
Total Accepted: 7402 Total Submissions: 19069My SubmissionsQuestion Solution
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.
Hide Tags
Tree
Hide Similar Problems
(M) Lowest Common Ancestor of a Binary Tree
Have you met this question in a real interview?
Yes
No
Discuss
思路,先判断入口是否有非法输入。
1 如果某一个root==p || root == q,那么LCA肯定是root(因为是top down,LCA肯定在root所囊括的树上,而root又是p q其中一个节点了,那么另外一个节点肯定在root之下,那么root就是LCA),那么返回root
2 如果root<min(p, q),那么LCA肯定在右子树上,那么递归
3 如果max(p, q)<root,那么LCA肯定在左子树上,那么递归
4 如果p<root<q,那么root肯定为LCA
以下代码仅为自己记录。
#include<iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; TreeNode* L; int digui(TreeNode* root,TreeNode* p,TreeNode* q) { if(root==p||root==q) { L=root; return 0; } else { if(root->val<p->val&&root->val<q->val) { int a,b; if(root->right!=NULL) b=digui(root->right,p,q); return a+b; } else if(root->val>p->val&&root->val>q->val) { int a,b; if(root->left!=NULL) b=digui(root->left,p,q); return a+b; } else { L=root; return 0; } } } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { digui(root,p,q); return L; } int main() { }
相关文章推荐
- js中跨域方法原理详解
- linux——samba服务器的配置
- HDU 1203 I NEED A OFFER!(01背包)
- 卸载 Apache方法
- 用Jsoup解析静态网页数据
- javaAPI(Sting)
- hdfs 文件的追加
- HDU 4607 Park visit (求树的直径)
- ZOJ 3627 Treasure Hunt II (贪心)
- 斐波那契数列
- 一个性能较好的jvm参数配置以及jvm的简介
- ActiveMQ消费者接收消息的过程
- HDU 2604 Queuing
- IBatis.net初步使用
- mysql在存储过程中从结果集给多个参数赋值的办法
- [LeetCode][Java] Largest Rectangle in Histogram
- codevs1042
- android自定义button样式
- 转:抗锯齿方法两种(其一:paint.setAntiAlias(ture);paint.setBitmapFilter(true))
- 将博客搬至CSDN