Leetcode 236

题目

在这里插入图片描述

题解

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':        
         def find_node(root,p,q):         
            if not root:             
               return None           
            if root==p or root==q:           
                 return root            
            left = find_node(root.left,p,q)            
            right = find_node(root.right,p,q)            
            if not left:          
                  return right            
            elif not right:             
                  return left           
            else:            
                return root        
          return find_node(root,p,q)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Pang_ling/article/details/106003573