No.236 Lowest Common Ancestor of a Binary Tree
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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Explanation:
找出二叉搜索树两个结点的最近公共祖先。
My Thinking:
My Solution:
Optimum Thinking:
- 使用递归,利用二叉搜索树左小右大的性质,若p和q都小(大)于当前结点,则对当前结点的左(右)子树进行递归,如果p和q都不同时大于或小于当前结点,说明两个结点从当前结点开始分叉,即当前结点就是最小祖宗。
- 对root进行迭代,和递归条件一样,迭代到p和q都不同时大于或小于当前结点。
- 网友更简洁的答案。
Optimum Solution:
(1)
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(p.val < root.val && q.val < root.val)
return lowestCommonAncestor(root.left, p, q);
else if(p.val > root.val && q.val > root.val)
return lowestCommonAncestor(root.right, p, q);
else
return root;
}
}
(2)
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while(root!=null){
if(p.val > root.val && q.val > root.val)
root = root.right;
else if(p.val < root.val && q.val < root.val)
root = root.left;
else
return root;
}
return null;
}
}
(3)
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while ((root.val - p.val) * (root.val - q.val) > 0)//p、q同时大于或小于root
root = p.val < root.val ? root.left : root.right;
return root;
}