zoukankan      html  css  js  c++  java
  • [LeetCode] 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 (root->val < p->val && root->val < q->val) {
                return lowestCommonAncestor(root->right, p, q);
            } else if (root->val > p->val && root->val > q->val) {
                 return lowestCommonAncestor(root->left, p, q);
            } else {
                return root;
            }
     
        }
    };
  • 相关阅读:
    再叙存储设备
    分布式文件系统---测试
    分布式文件系统
    Solr 分布式(复制)配置--成功验证
    搜索服务之离线处理思路
    我为公司做的总体架构,欢迎提建议
    python的面向对象
    python异常处理
    迭代器和生成器
    python函数
  • 原文地址:https://www.cnblogs.com/vincently/p/4778970.html
Copyright © 2011-2022 走看看