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).”
Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
_______6______ / ___2__ ___8__ / / 0 _4 7 9 / 3 5
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 nodes2
and8
is6
.
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 nodes2
and4
is2
, since a node can be a descendant of itself according to the LCA definition.
Note:
- All of the nodes' values will be unique.
- p and q are different and both values will exist in the BST.
求二叉搜索树(BST)的最近公共祖先(LCA)。最近公共祖先是指在一个树或者有向无环图中同时拥有v和w作为后代的最深的节点。
解法1:递归,
1. P, Q都比root小,则LCA在左树,我们继续在左树中寻找LCA
2. P, Q都比root大,则LCA在右树,我们继续在右树中寻找LCA
3. 其它情况,表示P,Q在root两边,或者二者其一是root,或者都是root,这些情况表示root就是LCA,直接返回root即可。
解法2: 迭代
判断标准同解法1,只是用迭代来实现。
Java:
public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q); if(root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q); return root; } }
Java:
public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { //发现目标节点则通过返回值标记该子树发现了某个目标结点 if(root == null || root == p || root == q) return root; //查看左子树中是否有目标结点,没有为null TreeNode left = lowestCommonAncestor(root.left, p, q); //查看右子树是否有目标节点,没有为null TreeNode right = lowestCommonAncestor(root.right, p, q); //都不为空,说明做右子树都有目标结点,则公共祖先就是本身 if(left!=null&&right!=null) return root; //如果发现了目标节点,则继续向上标记为该目标节点 return left == null ? right : left; } }
Python:
class Solution: # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): s, b = sorted([p.val, q.val]) while not s <= root.val <= b: # Keep searching since root is outside of [s, b]. root = root.left if s <= root.val else root.right # s <= root.val <= b. return root
C++:
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (!root) return NULL; if (root->val > max(p->val, q->val)) return lowestCommonAncestor(root->left, p, q); else if (root->val < min(p->val, q->val)) return lowestCommonAncestor(root->right, p, q); else return root; } };
C++:
class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { while (true) { if (root->val > max(p->val, q->val)) root = root->left; else if (root->val < min(p->val, q->val)) root = root->right; else break; } return root; } };
类似题目:
[LeetCode] 236. Lowest Common Ancestor of a Binary Tree 二叉树的最近公共祖先