68-II. The nearest common ancestor of the binary search tree (simple)

Title description:

Given a binary tree, find the nearest common ancestor of two specified nodes in the tree. The definition of the nearest common ancestor in Baidu Encyclopedia is: "For two nodes p and q of the rooted tree T, the nearest common ancestor is expressed as a node x, so that x is the ancestor of p and q and the depth of x is as large as possible (A node can also be its own ancestor)."

For example, given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]

Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The nearest of node 5 and node 1 The common ancestor is node 3.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The nearest common ancestor of node 5 and node 4 is Node 5. Because by definition the nearest common ancestor node can be the node itself.

# 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
        """
        # 递归
        # 如果p、q的值和根节点相同,那么直接返回根节点
        # 如果root是None,直接返回None
        # 在root这条线上继续寻找,如果左边没找到,说明在右边
        # 如果右边没找到说明在左边
        if not root:return None
        if p.val ==root.val or q.val==root.val:return root
        l=self.lowestCommonAncestor(root.left,p,q)
        r=self.lowestCommonAncestor(root.right,p,q)

        return root if l and r else l or r

 

Guess you like

Origin blog.csdn.net/weixin_38664232/article/details/105013624