[LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:网络协议实验报告 编辑:程序博客网 时间:2024/05/22 13:43
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
找出BST中的两节点的最低公共祖先
充分利用BST特性,如果p、q均在同一子树上,那么p、q的val与root的val的关系相同,或者root的val等于p或q
递归非递归的区别在于注意处理比较p、q、root的时候,分别是大于零和小于一
public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while ((root.val - p.val) * (root.val - q.val) > 0) { root = root.val > p.val ? root.left : root.right; } return root; }}
public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { return ((root.val - p.val) * (root.val - q.val) < 1) ? root : lowestCommonAncestor(root.val > p.val ? root.left : root.right, p, q); }}
0 0
- LeetCode 235. 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
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree LeetCode
- LeetCode 235. 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
- LeetCode 235. 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
- leetcode:235. 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
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- leetcode-235. Lowest Common Ancestor of a Binary Search Tree
- 235.[Leetcode]Lowest Common Ancestor of a Binary Search Tree
- 【leetcode】235. Lowest Common Ancestor of a Binary Search Tree
- 【2月2日】设计模式:静态代理
- 网络流题目集锦
- spingIoc注解方式之通常运用
- 欢迎使用CSDN-markdown编辑器
- 滴,学生卡||终于自学完了C++
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- mysql批量修改字符集
- 计算几何题目集锦
- 开篇--2017年计划
- 云服务器Window Server 2012R系统安装MySQL
- 38-1-2
- ssm整合中出现illegalargumentexception、NosuchbeansException解决
- PLSQL Trigger :OLD :NEW
- 6.4响应首部字段