Leetcode_235_Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:知乎保存的图片在哪 编辑:程序博客网 时间:2024/06/07 02:35
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/48392713
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 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
思路:
(1)题意为给定一个BST以及该树上两节点,求这两节点的最近公共祖先。
(2)该题比较简单,通过递归很好实现。如果两节点分别分布在根节点的左右子树上,那么它们的最近公共祖先只能是树根;如果两节点同时分部在根节点的相同子树上,则需要分别递归进行判定。
(3)详情见下方代码。希望本文对你有所帮助。
算法代码实现如下:
package leetcode;import leetcode.utils.TreeNode;/** * * @author liqqc * */public class Lowest_Common_Ancestor_of_a_Binary_Search_Tree {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {// 在树的两边if (p.val >= root.val && q.val <= root.val)return root;else if (p.val <= root.val && q.val >= root.val)return root;// 在树的一边 左边或右边else if (p.val < root.val && q.val < root.val) {// 左边return lowestCommonAncestor(root.left, p, q);}else {// 右边return lowestCommonAncestor(root.right, p, q);}}}
- Leetcode_235_Lowest Common Ancestor of a Binary Search Tree
- LeetCode_Lowest Common Ancestor of a Binary Search Tree (Binary Tree)
- Lowest Common Ancestor of a Binary Search Tree
- leetcode 235: Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree (235)
- Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree leetcode235
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree
- leetcode: Lowest Common Ancestor of a Binary Search Tree
- [leetcode][dfs] Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235.Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235 Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235.Lowest Common Ancestor of a Binary Search Tree
- 安装配置PHP 5.6 + Nginx 1.8
- UIpickerView
- 如何实施敏捷开发
- iOS中键值编码KVC的学习
- Altium Designer原理图中放置文本、图片、直线、拷贝、智能粘贴
- Leetcode_235_Lowest Common Ancestor of a Binary Search Tree
- HD 2041 Baskets of Gold Coins
- 快速排序
- 关于 configure.in 文档中的若干笔记
- CCF 201409-2 画图 题解
- kamailio服务器内容补充
- Rythem——Mac OS下简单易用类似fiddler的抓包工具
- 数据结构实践项目——链表
- 第二周项目1-C/C++语言中函数参数传递的三种方式