Skip to content

Commit

Permalink
递归实现
Browse files Browse the repository at this point in the history
  • Loading branch information
rinwf committed Dec 23, 2018
1 parent 8116a84 commit e4728d3
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Lowest Common Ancestor of a Binary Tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# 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, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if not root or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return left if left else right

0 comments on commit e4728d3

Please sign in to comment.