• 【ACM从零开始】LeetCode OJ-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.

    题目大意:给出两个二叉树的结点,寻找这两个结点最近的那个公共父结点(LCA)。比如如图,结点“2”和“8”的LCA是6,结点“2”和“4”的LCA是2。

    解题思路:

    这题要结合二叉树的规律,即左孩子小于根结点小于右孩子。所以当给出的结点p和q,如果p,q<root,则LCA必在左子树;如果p<root<q,则LCA为root;如果root<p,q,则LCA必在右子树。

    结合三种情况,首先求出结点p和结点q中较大的那个,与root进行比较,如果比root小,遍历左子树;如果比root大,遍历右子树;都不满足,返回root。

    AC代码:

    class Solution {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            if(!root || !p || !q)return NULL;
            if(p->val < root->val && q->val < root->val)
                lowestCommonAncestor(root->left,p,q);
            else if(p->val > root->val && q->val > root->val)
                lowestCommonAncestor(root->right,p,q);
            else
                return root;
        }
    };

  • 相关阅读:
    Yii2 在模块modules间跳转时,url自动加模块名
    PHP 变量的间接引用(将某一字符串转化为变量)
    windows鼠标悬停任务栏 延迟时间 修改
    dede 常用标签和调用方法汇总
    dedecms ---m站功能基础详解
    apache 2.2 和2.4 目录权限访问设置的区别
    apache httpd.conf 配置局域网访问
    ajax php 点击加载更多
    dede调用当前栏目名 、dede sql
    dede 添加 栏目缩略图
  • 原文地址:https://www.cnblogs.com/shvier/p/4869261.html
Copyright © 2020-2023  润新知