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).”
Example 1:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6.
Example 2:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
Example 3:
Input: root = [2,1], p = 2, q = 1 Output: 2
Constraints:
- The number of nodes in the tree is in the range
[2, 105]
. -109 <= Node.val <= 109
- All
Node.val
are unique. p != q
p
andq
will exist in the BST.
费劲吧啦做出来,一看难度竟然是简单,不知道是我想多了还是难度标错了。方法其实就是递归查找,根据返回值来判断该返回什么结果。细分的话其实也就下面几种情况:
1. root==p, q在root的left subtree.
2. root==p, q在root的right subtree.
3. root==q, p在root的left subtree.
4. root==q, p在root的right subtree.
5. p, q分别在root的left subtree和right subtree.
代码(Rust):
impl Solution {
fn find(
root: &Option<Rc<RefCell<TreeNode>>>,
p: i32,
q: i32,
) -> (bool, bool, Option<Rc<RefCell<TreeNode>>>) {
if let Some(node) = root {
if node.borrow().val == p {
let (_, left_q, _) = Solution::find(&node.borrow().left, p, q);
if left_q {
return (true, true, Some(node.clone()));
}
let (_, right_q, _) = Solution::find(&node.borrow().right, p, q);
if right_q {
return (true, true, Some(node.clone()));
}
return (true, false, None);
}
if node.borrow().val == q {
let (left_p, _, _) = Solution::find(&node.borrow().left, p, q);
if left_p {
return (true, true, Some(node.clone()));
}
let (right_p, _, _) = Solution::find(&node.borrow().right, p, q);
if right_p {
return (true, true, Some(node.clone()));
}
return (false, true, None);
}
let (left_p, left_q, left_ancestor) = Solution::find(&node.borrow().left, p, q);
if left_ancestor.is_some() {
return (true, true, left_ancestor);
}
let (right_p, right_q, right_ancestor) = Solution::find(&node.borrow().right, p, q);
if right_ancestor.is_some() {
return (true, true, right_ancestor);
}
if (left_p && right_q) || (right_p && left_q) {
return (true, true, Some(node.clone()));
} else {
if left_p || right_p {
return (true, false, None);
} else if left_q || right_q {
return (false, true, None);
} else {
return (false, false, None);
}
}
}
return (false, false, None);
}
pub fn lowest_common_ancestor(
root: Option<Rc<RefCell<TreeNode>>>,
p: Option<Rc<RefCell<TreeNode>>>,
q: Option<Rc<RefCell<TreeNode>>>,
) -> Option<Rc<RefCell<TreeNode>>> {
let (_, _, node) = Solution::find(&root, p.unwrap().borrow().val, q.unwrap().borrow().val);
return node;
}
}