zoukankan      html  css  js  c++  java
  • 235.Lowest Common Ancestor of a Binary Search Tree


    给定一个二叉搜索树,以及2个节点p, q ,求这两个节点的最近公共祖先。

    Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
    Output: 6
    Explanation: The LCA of nodes 2 and 8 is 6.

    Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
    Output: 2
    Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

    思路:
    一、因为是二叉搜索树,所以中序遍历是已经排好序的如果p, q的值都比根节点小,则最近祖先节点在根节点左边,反之,在根节点右边;如果其中一个比根节点小,另一个比根节点大,则根节点就是最近祖先。对于其中一个节点的值等于根节点,则根节点也是最近祖先。题目说了一定存在最近祖先,所以不用考虑节点为空、不存在的情况。

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root->val == p->val || root->val == q->val) return root;
        if (root->val > p->val && root->val < q->val) return root; //  p < root < q
        if (root->val > q->val && root->val < p->val) return root; //  q < root < p
        if (root->val > p->val && root->val > q->val) return lowestCommonAncestor(root->left, p, q);
        return lowestCommonAncestor(root->right, p, q);
    }

    二、如果不考虑二叉搜索树,将二叉树当作无序的普通二叉树。
    则,当前节点与其中任意一个节点相等时,返回当前节点。
    当前节点的左子树搜索有返回结果,且右子树搜索也有返回结果,则当前节点就是最近公共祖先,返回当前节点。
    当前节点的一边子树搜索有结果,而另一边返回为null,返回有结果的子树上返回的结果,所以,需要一个变量来保存子树搜索的结果
    如果都为左右子树搜索结果都为null,返回null.

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (!root) return NULL;
        if (root == p || root == q) return root;
        TreeNode* left_res = lowestCommonAncestor(root->left, p, q);
        TreeNode* right_res = lowestCommonAncestor(root->right, p, q);
        if (left_res && right_res) return root;
        return left_res ? left_res : right_res;
    }

    Java 版:

    class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if(p.val > q.val){
                TreeNode tmp = p;
                p = q;
                q = tmp;
            }
            if(p.val <= root.val && q.val >= root.val) return root;
            if(p.val < root.val && q.val < root.val) return lowestCommonAncestor(root.left, p,q);
            return lowestCommonAncestor(root.right, p,q);
        }
    }
  • 相关阅读:
    Angular Universal 学习笔记
    SAP Spartacus 如何获得当前渲染页面的 CMS 元数据
    Angular 服务器端渲染的学习笔记(二)
    Angular 服务器端渲染的学习笔记(一)
    第三方外部 Saas提供商如何跟使用 SAP 系统的客户进行对接接口集成
    如何从 SAP Spartacus Product Detail 页面,找到其 Angular 实现 Component 的位置
    具备自动刷新功能的 SAP ABAP ALV 报表
    C++学习目录
    c--条件编译
    c--文件读写--二进制
  • 原文地址:https://www.cnblogs.com/luo-c/p/12878479.html
Copyright © 2011-2022 走看看