LeetCode------Lowest Common Ancestor of a Binary Search Tree
2016-05-03 10:53
393 查看
题目简介
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.
给定一个二进制搜索树(BST),找到最近公共祖先(LCA)的两个给定节点的成就。
根据维基百科的定义:“最近公共祖先是定义两节点v和w之间最低的节点不具有V和W的后裔(我们允许一个节点有自己的后裔)。”
例如,最近的公共祖先(LCA)节点2和8是6。另一个例子是LCA节点2和4是2,因为一个节点可以是自己根据LCA的定义。
自己的解法
public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(p.val == root.val||q.val ==root.val) return root; while(true){ TreeNode leftroot =findCurrent(root, p); TreeNode rightroot =findCurrent(root, q); if(leftroot != null&&leftroot.val == q.val) return leftroot; else if(rightroot !=null&&rightroot.val == p.val) return rightroot; else if(leftroot != null&&rightroot != null&&leftroot.val == rightroot.val) return leftroot; p = leftroot; q = rightroot; } } public TreeNode findCurrent(TreeNode root, TreeNode p){ if(p.val == root.val) return root; if(root == null) return root; else{ TreeNode left = root.left; TreeNode right = root.right; if(left != null&&left.val == p.val) return root; else if(right !=null&&right.val == p.val) return root; else if(p.val <root.val) return findCurrent(left,p); else return findCurrent(right,p); } } }
题目的意思是寻找一棵二叉排序数的两个节点的最近祖先,这个最近祖先可以包含它自己。我的思路是这样的通过findCurrent函数找到任意一个节点的祖先节点,然后再主函数里判断,如果没找到的话,继续寻找祖先节点的祖先节点。我提交一直有问题,原因是这样的,比如这样一棵二叉排序树[5,3,6,2,4,null,null,1],给的节点是1和3,按照我的算法返回的是5而正确的节点是3。我的算法如果要寻找的节点某一棵刚好是另一棵的祖先节点,就无法返回正确答案。一般都会返回根节点。
Hot解法
public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while ((root.val - p.val) * (root.val - q.val) > 0) root = p.val < root.val ? root.left : root.right; return root; } }
Hot解法的代码还是如此的简介,它的主要思路就是一个规律,这两个节点最近的祖先节点,一个节点要比祖先节点的大,另一个要比祖先节点的小。如果不是,那说明这两个节点在同一侧,那么进行递归。
感受:做编程题目,思考往往比敲代码更重要。如果你有一个很好的思路,那么敲起代码来往往是很快的的。如果你的思路不清晰,那么你肯定会跑一次改一次,运气好最后可以通过。运气不好你是无法改对的,因为你的思路就是有问题的。所有我建议大家开始做题前先要进行足够的思考,不要一上来就急着敲代码,如果你的想法够好,那么敲起来代码肯定是事半功倍的。
相关文章推荐
- 二叉查找树
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例