zoukankan      html  css  js  c++  java
  • 【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的情况,因此代码中省去了空指针的判断。

  • 相关阅读:
    IOS知识点收集
    多媒体层预览(Media Layer OverView)
    IOS Audio开发集合
    《android 1: 创建一个安卓项目》
    IOS 中的CoreImage框架(framework)
    [转载]面向对象的六大原则
    [转载]UDP丢包率提升
    产品与项目的区别
    关联、组合、聚合、依赖关系比较
    统一建模语言(UML,Unified Modeling Language)
  • 原文地址:https://www.cnblogs.com/jdneo/p/4739680.html
Copyright © 2011-2022 走看看