• leetcode刷题笔记 236题 二叉树的最近公共祖先


    leetcode刷题笔记 236题 二叉树的最近公共祖先

    源地址:236. 二叉树的最近公共祖先

    问题描述:

    给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

    百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

    例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]

    示例 1:

    输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
    输出: 3
    解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
    示例 2:

    输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
    输出: 5
    解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。

    说明:

    所有节点的值都是唯一的。
    p、q 为不同节点且均存在于给定的二叉树中。

    //本题思路主要参考题解 https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/236-er-cha-shu-de-zui-jin-gong-gong-zu-xian-hou-xu/
    //通过递归方法 自底向上 确定每个节点的属性
    //根据每个节点左右子树情况,具体可分为四种情况
    //1.左右均为null(p q均不在) 返回null
    //2.左不为null 右为null 返回左
    //3.左为null 右不为null 返回右
    //4.左右均不为null 返回root
    /**
     * Definition for a binary tree node.
     * class TreeNode(var _value: Int) {
     *   var value: Int = _value
     *   var left: TreeNode = null
     *   var right: TreeNode = null
     * }
     */
    
    object Solution {
        def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = {
            if (root == null || root == p || root == q) return root
            val left = lowestCommonAncestor(root.left, p, q)
            val right = lowestCommonAncestor(root.right, p, q)
            if (left == null) return right
            if (right == null) return left
            return root 
        }
    }
    
  • 相关阅读:
    日期格式不合法
    DataGridView的Scrollbar通過編程不能自動下滾
    Sourcesafe shadown backup
    共享目錄突然不工作 
    VS2005編譯后版本如何控制
    WebBrowser用作RichTextBox
    怎樣設定MS Reporting自動橫向列印
    VSS 2005不需登錄,直接開啟的方法
    subreport cannot be shown
    An Algorithm Summary of Programming Collective Intelligence (5)
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13868188.html
Copyright © 2020-2023  润新知