LeetCode-Lowest Common Ancestor of a Binary Search Tree
2015-10-20 20:14
369 查看
Problem:
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.
Analysis:
这个是二叉搜索树的题,根据二叉搜索树的特点可知:
那么我们只要判断p和q是否在root的左右分支或者p和q中的一个是root即可。
但是p和q哪个大并不清楚,这里有个绝招:
Anwser1: 利用死循环查找
Anwser2: 利用递归查找
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.
Analysis:
这个是二叉搜索树的题,根据二叉搜索树的特点可知:
root.val<root.right.val 且 root.left.val<root.val
那么我们只要判断p和q是否在root的左右分支或者p和q中的一个是root即可。
但是p和q哪个大并不清楚,这里有个绝招:
(root.val-p.val)*(root.val-q.val)<=0
Anwser1: 利用死循环查找
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while(root!=null){ if((root.val-p.val)*(root.val-q.val)<=0) return root; else if(root.val>p.val) root=root.left; else root=root.right; } return null; } }
Anwser2: 利用递归查找
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if((root.val-p.val)*(root.val-q.val)<=0) return root; else if(root.val>p.val) return lowestCommonAncestor(root.left,p,q); else return lowestCommonAncestor(root.right,p,q); } }
相关文章推荐
- opencv2-遍历图像像素的14种方法
- IOS 基于APNS消息推送原理与实现
- 输入输出
- 结构体名与结构体类型名,可以一样吗?
- Calendar在Java中详细
- string::npos
- iOS开发4-NSURLConnection实现Http通信
- 异常处理
- zoj3735Josephina and RPG
- 软考——加密与认证技术
- Android EditText添加图片
- Spark shell脚本
- 运行循环RunLoop原理剖析
- UI - UICollectionView
- sicily 1093. Air Express
- hdu2188 悼念512汶川大地震遇难同胞——选拔志愿者
- Driver Signing changes in Windows 10
- 我们应该开发怎么样的电子签章产品
- 【bzoj4300】【绝世好题】
- zoj3762Alice's Print Service