1. 程式人生 > >LeetCode236:Lowest Common Ancestor of a Binary Tree

LeetCode236: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

).”

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

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         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 LCA of of nodes 5 and 1 is 3.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself
             according to the LCA definition.

Note:

  • All of the nodes' values will be unique.
  • p and q are different and both values will exist in the binary tree.

LeetCode:連結

參考:連結1     連結2

第一種方法:DFS分別尋找到兩個節點p和q的路徑,然後對比路徑,檢視他們的第一個分岔口,則為LCA。和LeetCode235:Lowest Common Ancestor of a Binary Search Tree的第三種通用方法是一個思路。

dfs查詢的是必須傳入path列表!!!

# 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
        """
        pathp, pathq = [], []
        self.findpath(root, p, pathp)
        self.findpath(root, q, pathq)
        res = root
        for i in range(min(len(pathp), len(pathq))):
            if pathp[i] == pathq[i]:
                res = pathp[i]
        return res
        
    def findpath(self, root, p, path):
        if root == None:
            return False
        path.append(root)
        if root == p:
            return True
        if self.findpath(root.left, p, path):
            return True
        if self.findpath(root.right, p, path):
            return True
        path.pop()
        return False

node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
node6 = TreeNode(6)
node7 = TreeNode(7)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node3.right = node7

S = Solution()
path = []
print(S.findpath(node1, node7, path))
print(path)

第二種方法:遞迴尋找兩個帶查詢LCA的節點p和q,當找到後,返回給它們的父親。如果某個節點的左右子樹分別包括這兩個節點,那麼這個節點必然是所求的解,返回該節點。否則,返回左或者右子樹(哪個包含p或者q的就返回哪個)。

# 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
        """
        #若root為空或者root為A或者root為B,說明找到了A和B其中一個
        if root == None or root == p or root == q:
            return root 
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        #若左子樹找到了A,右子樹找到了B,說明此時的root就是公共祖先
        if left and right:
            return root
        #返回左或者右子樹(哪個包含p或者q的就返回哪個)
        return left if left else right