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

    https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/#/description

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

    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).”

            _______3______
           /              
        ___5__          ___1__
       /              /      
       6      _2       0       8
             /  
             7   4
    

    For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

    Sol:

    Bottom-up.

    Find where is p or q. 

    1) if p or q is the root, return root

    2) if p and q are on both sides of the tree, return root

    3) if p and q are on left subtree, return left node.

    4) if p and q are on right subtree, return right node.

    To make the logic of 3) and 4) more apprent to computers, we use left/right variables to check if p and q exist on left/right subtree. # simple discrete mathematics 

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def lowestCommonAncestor(self, root, p, q):
            """
            :type root: TreeNode
            :type p: TreeNode
            :type q: TreeNode
            :rtype: TreeNode
            """
            # if root is null or find p or q
            if root == None or root == q or root == p:
                return root
            # find p or q in the left subtree
            left = self.lowestCommonAncestor(root.left, p, q)
            # find p or q in the right subtree
            right = self.lowestCommonAncestor(root.right, p, q)
            
            if left and right:
                return root
            else:
                if not left:
                    return right
                else:
                    return left

    Similar Problem:

    235. Lowest Common Ancestor of a Binary Search Tree

    In the BSTproblem, we use the one BST attribute, values of p and q, to check which side p and q are on. We can also use iteration on it.   

  • 相关阅读:
    决策树和随机森林
    6个开源数据科学项目
    机器学习:梯度下降
    Python中的数据结构
    方差分析介绍(结合COVID-19案例)
    html5
    归并排序
    前端与后端
    Dw3 Sublime text 3 UltraEdit XAMMPP 火狐浏览器 ISS
    ECMAScript JavaScript JScript
  • 原文地址:https://www.cnblogs.com/prmlab/p/7141442.html
Copyright © 2011-2022 走看看