python --- LeetCode之 236. Lowest Common Ancestor of a Binary Tree

题目:
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
题目理解:
题目就是要找到二叉树中两个节点的最近公共节点。
方法:
递归,用一个辅助函数以此节点为根结点找p和q,如果在左子树找到p(q),右子树找到q(p),则此节点即为所求,如果在左子树(右子树)找到p和q,则左子树(右子树)停止寻找,返回该节点的右节点(左节点),在右子树(左子树)继续寻找,直到p和q分别在左子树和右子树,则此时的节点即为所求。
代码:

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        return self.heaper(root,p,q)
    def heaper(self, node, p, q):
        if node == None or node ==p or node == q:
            return node
        left = self.heaper(node.left,p,q)   # 如果左子树找到目标节点,则返回左节点,否则就是None
        right = self.heaper(node.right,p,q) # 如果右子树找到目标节点,则返回右节点,否则就是None
        if left and right:
            return node
        if left and not right:   # if left is not None and right is None:
            return left
        if not left and right:
            return right

你可能感兴趣的:(python --- LeetCode之 236. Lowest Common Ancestor of a Binary Tree)