LeetCode(235) Lowest Common Ancestor of a Binary Search Tree解题报告
2015-12-16 10:24
435 查看
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 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.
解题思路:
因为是BST,所以很好判断,如果root比p,q任何一个都小,那么LCA一定在右子树上,递归,反之,在左子树,如果正好比一个大,比一个小,那么LCA就是root
下面分别附上递归和迭代解法:
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.
解题思路:
因为是BST,所以很好判断,如果root比p,q任何一个都小,那么LCA一定在右子树上,递归,反之,在左子树,如果正好比一个大,比一个小,那么LCA就是root
下面分别附上递归和迭代解法:
public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root.val < Math.min(p.val, q.val)) return lowestCommonAncestor(root.right,p,q); if(root.val > Math.max(p.val, q.val)) return lowestCommonAncestor(root.left,p,q); return root; } }
public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while(true){ while(root.val < Math.min(p.val,q.val)){ root = root.right; } while(root.val > Math.max(p.val,q.val)){ root = root.left; } while(root.val <= Math.max(p.val, q.val) && root.val >= Math.min(p.val,q.val)) return root; } } }
相关文章推荐
- 定制Linux内核 发挥Linux潜能
- iOS 开发之 runtime运行时模拟成员变量
- toString方法
- R语言学习
- 图像矫正----认识畸变(Distortion)
- eclipse构建及运行maven web项目
- 异常解决:util.NativeCodeLoader: Unable to load native-hadoop library for your platform
- 动态规划之0-1背包问题
- C#拓展方法
- SharePoint Permission Analyzer 权限分析仪
- ios集成语音朗读功能
- 基于JavaScript获取鼠标位置的各种方法
- 线程池的理解
- Webstorm的快捷键
- Linux的inode的理解
- 抽象概括能力
- QDataTime的一些使用概述
- android源码分析(ZZ)
- WIZnet通过启动在线培训活动:计算机网络TCP/IP协议而事实上,现在的方法
- 运维排查问题的方法和脚本