235. Lowest Common Ancestor of a Binary Search Tree*
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
题目描述
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]
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.
Note:
- All of the nodes’ values will be unique.
p
andq
are different and both values will exist in the BST.
C++ 实现 1
递归实现. 注意 Note 中说所有节点的值是 unique 的, 此外, p 和 q 的值不同并且肯定在 BST 中, 所以 BST 不为空. 如果 p 和 q 一个在左子树, 而另一个在右子树, 那么 LCA 肯定就是根节点. 如果它们同在左子树, 或者同在右子树, 那么只需要递归去寻找即可.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if ((p->val <= root->val && q->val >= root->val) || (p->val >= root->val && q->val <= root->val))
return root;
if (p->val < root->val && q->val < root->val)
return lowestCommonAncestor(root->left, p, q);
if (p->val > root->val && q->val > root->val)
return lowestCommonAncestor(root->right, p, q);
return nullptr;
}
};
C++ 实现 2
迭代实现, 其实思路和 C++ 实现 1
一致.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode *node = root;
while (node) {
int val = node->val;
if (p->val < val && q->val < val) node = node->left;
else if (p->val > val && q->val > val) node = node->right;
else return node;
}
return nullptr;
}
};
来源:CSDN
作者:珍妮的选择
链接:https://blog.csdn.net/Eric_1993/article/details/104523226