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

Title description:

Given a binary search 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 search tree: root = [6,2,8,0,4,7,9,null,null,3,5]

Example 1:

Input: the root = [6,2,8,0,4,7,9, null, null, 3,5], P = 2, Q =. 8
 Output: 6 
 Explanation: node 2 and the node 8 common ancestor is6。

Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
 Output: 2
 Explanation: The nearest common ancestor of node 2 and node 4 is 2, 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
        """
        if not root:return None
        if p.val == q.val:return p
        while root:
            if root.val < p.val and root.val <q.val:
                root=root.right
            if root.val > p.val and root.val > q.val:
                root=root.left
            else:
                return root

 

Guess you like

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