【LeetCode】235. 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 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.

提示:

此题的核心是要利用已知条件中,给定的二叉树是二叉搜索树这一条件。所谓二叉搜索树,指的是一种二叉树,其中,比根节点小的节点都位于根节点的左侧,反之,若比根节点要大,则位于根节点的右侧。可以参考题目中的例子。

递归调用的思路也很简单:

  • 若两个要搜索的节点都比根节点小,则对根节点的左节点进行递归;
  • 若两个要搜索的节点都比根节点打,则对根节点的右节点进行递归;
  • 若一大一小,则返回根节点。

代码:

/**
* 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)
return lowestCommonAncestor(root->left, p, q);
if (p->val > root->val && q->val > root->val)
return lowestCommonAncestor(root->right, p, q);
return root;
}
};

由于此题的测试用例中没有节点为NULL的情况,因此代码中省去了空指针的判断。

上一篇:mysql建立高效索引分析


下一篇:mysql建立索引的几大原则