题目:
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).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
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.
翻译:
给定一棵二叉搜索树(BST),对于该BST中的两个节点,找到他们具有最低高度的共同祖先(LCA)。
根据维基百科上LCA的定义:“最低高度的共同祖先被定义为在两个节点 v 和 w 之间最低节点 T 既有后代 v ,又有后代 w (允许一个节点是它本身的后代)。”举例,对于节点2和8的最低高度共同祖先(LCA)是6。另一个例子是对于节点2和4的LCA是2,因为根据LCA的定义,一个节点可以是它自己本身的后代。
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
思路:
显而易见要使用递归求解,另外因为题中给定是一棵二叉搜索树,因此这棵树具有以下特点:所有节点的左孩子的值都小于当前节点,而右孩子的值都大于当前节点。因此,利用这一有用信息,现在对于给定的两个节点 p 和 q ,若他们中一个值大于根节点,而另一个值小于根节点,那么他们的最低高度共同祖先就是根节点;若他们的值都小于根节点,那么他们的LCA在根节点的左孩子中,相反,若他们的值都大于根节点,那么他们的LCA在根节点的右孩子中。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
using namespace std;
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) {
return lowestCommonAncestor(root->left,p,q);
}
if (p->val > root->val&&q->val > root->val) {
return lowestCommonAncestor(root->right,p,q);
}
return root;
}
};
int main()
{
Solution s;
TreeNode* result;
TreeNode* root=new TreeNode(6);
root->left = new TreeNode(2);
root->right = new TreeNode(8);
root->left->left = new TreeNode(0);
TreeNode* p=root->left->right = new TreeNode(4);
p->left = new TreeNode(3);
p->right = new TreeNode(5);
root->right->left = new TreeNode(7);
TreeNode* q = root->right->left = new TreeNode(9);
result = s.lowestCommonAncestor(root, p, q);
cout << result->val;
return 0;
}