leetcode 1644. Lowest Common Ancestor of a Binary Tree II(python)

Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-in Event, click to view the details of the event

describe

Given the root of a binary tree, return the lowest common ancestor (LCA) of two given nodes p and q. if either node p or q does not exist in the tree, return null. All values of the nodes in the tree are unique.According to the definition of LCA on Wikipedia: The lowest common ancestor of two nodes p and q in a binary tree T is the lowest node that has both p and q as descendants(where we allow a node to be a descendant of itself), A desendant of a node x is a node y that is on the path from node x to some leaf node.

Example 1:

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

Note

The number of nodes in the tree is in the range [2, 10^5].
-10^9 <= Node.val <= 10^9
All Node.val are unique.
p != q
p and q will exist in the tree.
复制代码

Parse

According to the meaning of the question, given the root of a binary tree, return the lowest common ancestor (LCA) of two given nodes p and q. Returns null if node p or q does not exist in the tree. The title guarantees that all values ​​of nodes in the tree are unique.

This question is actually basically the same as the idea of ​​[236. Lowest Common Ancestor of a Binary Tree]. If that question can be done, this question will definitely be done, and students who don’t understand can turn it over and take a look.

answer

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def __init__(self):
        self.result = None
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        def dfs(root, p, q):
            if not root: return 0
            left = dfs(root.left, p, q)
            right = dfs(root.right, p, q)
            self_ = 1 if (p == root or q == root) else 0
            count = left + right + self_
            if count == 2 and not self.result:
                self.result = root
            return count
        dfs(root, p, q)
        return self.result
        	      
		
复制代码

operation result

Runtime: 68 ms, faster than 63.65% of Python online submissions for Lowest Common Ancestor of a Binary Tree II.
Memory Usage: 29.9 MB, less than 8.97% of Python online submissions for Lowest Common Ancestor of a Binary Tree II . 
复制代码

Original title link: leetcode.com/problems/lo…

Your support is my greatest motivation

Guess you like

Origin juejin.im/post/7079596505408995365