leetcode 235 Lowest Common Ancestor oa a Binary Search Tree
来源:互联网 发布:提高数据分析能力 编辑:程序博客网 时间:2024/04/30 17:41
题目要求:给定一个二叉查找树中的两个节点,找出它们最低的共同祖先。
tags:tree,recursive
思路:
首先说说二叉查找树的特性:
1.比根节点小的节点都在左子树上,
2.比根节点大的节点都在右子树上,
3.查找树种没有两个相同的值。
非二叉查找树:
查找时需要记录查找路径,不然无法进行查找。(遍历)
做法:找到第一个值,使其可以大于等于左节点并小于等于右节点。
即,当根节点值大于左右节点时,它的最低共同祖先在根节点的左孩子上;当根节点小于左右结点时,最低共同祖先在根节点的右孩子上。
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root==null || p==null || q ==null){ return null; }else if(Math.max(p.val,q.val)<root.val){ return lowestCommonAncestor(root.left,p,q); }else if(Math.min(p.val,q.val)>root.val){ return lowestCommonAncestor(root.right,p,q); }else{ return root; } }
0 0
- leetcode 235 Lowest Common Ancestor oa 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
- 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
- 如何不停止服务清空nohup.out文件
- php常用代码大全
- iOS 分享(使用友盟sdk)
- 牛客网 | 数组中出现次数超过一半的数字
- POJ 2487 Stamps
- leetcode 235 Lowest Common Ancestor oa a Binary Search Tree
- FRM-40831错误的解决办法?
- scrollView中设置ImageView大小
- android资源目录---assets与res/raw区别
- Swift学习 下标脚本subscript和类扩展Extension
- 小随记
- Your project contains error(s),please fix them before running your application
- 对java类override的探讨
- 数字签名的加密解密过程 和 私有密钥的加密解密过程