leetcode——Lowest Common Ancestor of a Binary Search Tree
2015-08-11 20:24
381 查看
题目
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.思路
题目要求一个二叉排序树的两个节点的公共父节点,说通俗点,其实就是这两个节点所在的分支是从哪里开始分叉的。求出这个分叉点。对于二叉排序树,它的一个特点就是:一个节点的左子树节点都小于该节点,而一个节点的右子数的各节点都大于该节点。
因此,我们可以通过寻找这两个节点的中间节点来寻找公共父节点。
再衍生分析一下,如果某个节点同时大于所给节点,说明,所求节点一定在当前节点的左子树上;同理,如果当前节点同时小于所给的两个节点,则所求节点一定在该节点的右子树上。
需要注意的是:在求的过程中,还需要考虑如果所求节点是两个节点中的一个的情况。还有在求出当前节点时,别忘了验证一下,该节点为根的树上有没有这两个所给节点(因为有可能所给节点不在树上)。
代码
public boolean exist(TreeNode root, TreeNode pNode){ while(root!=null){ if(pNode.val==root.val) return true; else{ if(pNode.val>root.val) root = root.right; else { root = root.left; } } } return false; } public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { TreeNode currentNode = root; if(root==null) return null; while(currentNode!=p && currentNode!=q){ if(p.val<currentNode.val && q.val<currentNode.val){ currentNode = currentNode.left; } else if(p.val>currentNode.val && q.val>currentNode.val){ currentNode = currentNode.right; } else{ if(exist(currentNode, p) && exist(currentNode, q)) return currentNode; else { return null; } } } if(exist(currentNode, p) && exist(currentNode, q)) return currentNode; return null; }
相关文章推荐
- 基于ARP的监听
- 29-HTML-19-HTML(标签的分类)
- Java多态性理解
- Android单元测试异常总结---Test run failed:Unable to find instrumentation target package
- 10-2. 删除字符串中的子串(20)
- uva11752(合数)
- 8月11日----数据库、serverlet
- Linux管道命令(pipe)之选取命令grep
- 29-HTML-17-HTML(服务端和客户端校验的问题)
- 29-HTML-18-HTML(常见的其他标签)
- 矩形嵌套问题
- 第十五章 外中断
- Blue Jeans(POJ--3080
- 29-HTML-16-HTML(服务端GET和POST区别)
- 开放GIS标准OGC之路(3)之 WFS初探
- spring属性的注入实例
- 【KMP】hdu1867(A + B for you again) 杭电java a题真坑
- 7种寻址方式
- Constructing Roads
- O2O疯狂烧钱路:止血还是放血好