LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
2016-02-28 11:48
453 查看
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
Another example is LCA of nodes
since a node can be a descendant of itself according to the LCA definition.
分析:二叉排序树(又叫二叉查找树)或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
(4)没有键值相等的节点。(以上来自百度百科)
可以根据二叉排序树的特点,利用递归算法来解决:
代码:
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.
分析:二叉排序树(又叫二叉查找树)或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
(4)没有键值相等的节点。(以上来自百度百科)
可以根据二叉排序树的特点,利用递归算法来解决:
代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || p == null || q == null) return null; if(p.val < root.val && q.val < root.val){ return lowestCommonAncestor(root.left, p, q); } if(p.val > root.val && q.val > root.val){ return lowestCommonAncestor(root.right, p, q); } return root; } }
相关文章推荐
- <<第一行代码>>--根据程序当前界面判断是哪一个Activity
- 作为上帝,不要忘记奖励一下好人
- Fragment 的静态方式和动态方式以及动态方式中fragment之间通过activity传递 数据(接口回调 ):
- swap分区
- PAT (Top Level) Practise 1001 Battle Over Cities - Hard Version (35)
- python 写的一个爬虫程序源码
- HTML5 Canvas实现图片缩放、翻转、颜色渐变的代码示例
- mac nginx php fpm
- python学习笔记-Day6(1)
- 安装CUDA的风波
- free 与 delete
- servlet
- css全局设置
- 《leetCode》:Best Time to Buy and Sell Stock III
- Gson 设定固定的日期格式来生成Gson-------Gson 可以将某个对象转换成json,也可将json转换成对象
- python_Python中用format函数格式化字符串的用法
- tcp有限状态机
- java中array,arraylist,iterator;
- The 11th Zhejiang Provincial Collegiate Programming Contest->Problem G:G - Ternary Calculation
- 读写给大家看的项目管理书