LintCode 578. 最近公共祖先 III (Lowest Common Ancestor III) Python題解

Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.
The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
Return null if LCA does not exist.

樣例

Example1

Input: 
{4, 3, 7, #, #, 5, 6}
3 5
5 6
6 7 
5 8
Output: 
4
7
7
null
Explanation:
  4
 / \
3   7
   / \
  5   6

LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
LCA(5, 8) = null

Example2

Input:
{1}
1 1
Output: 
1
Explanation:
The tree is just a node, whose value is 1.

注意事項

node A or node B may not exist in tree.
Each node has a different value

 

AC代碼:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        this.val = val
        this.left, this.right = None, None
"""


class Solution:
    """
    @param: root: The root of the binary tree.
    @param: A: A TreeNode
    @param: B: A TreeNode
    @return: Return the LCA of the two nodes.
    """
    def lowestCommonAncestor3(self, root, A, B):
        if(root is None):
            return None
        #write your code here
        path = [root]
        f1, pathA = self.dfs(root, path, A)
        path = [root]
        f2, pathB = self.dfs(root, path, B)
        print(f1)
        print(f2)
        if((f1 and f2) == 0):#注意這裏符號運行的先後順序!!!
            return None
        for i in range(min(len(pathA),len(pathB)) - 1, -1, -1):
            if(pathA[i] == pathB[i]):
                return pathA[i]
        return None
        #return path[0]

    def dfs(self, root, path, target):
        if(root == target):
            #print(root.val)
            return 1, path
            
        if(root.left):
            path.append(root.left)
            #print("#")
            flag, path = self.dfs(root.left, path, target)
            if(flag == 1):
                return 1, path
            path.pop()
            
        if(root.right):
            path.append(root.right)
            #print("$")
            flag, path = self.dfs(root.right, path, target)
            if(flag == 1):
                return 1, path            
            path.pop()
        
        return 0, path
        
       

對於用dfs找特定點的路徑還是不是很熟練。不過這次基本上都是自己碼出來的代碼。思路是分別找到兩個點的路徑,如a = [4,7,6]和 b = [4,7,5,2],然後從最高的那個點的長度開始比較路徑,找到第一個相同點,如這裏在樹裏比較高的點是a,那麼就取a[2]和b[2]開始比較,不等(6和5),則 i -= 1,取a[1]和b[1],發現相等,則最近公共祖先爲7這個點。

 

注意點有一個, 主要是Python的語法問題。在代碼段中給予註釋了。若 f1 == 0, f2 == 0,那麼 (f1 and f2) == 0 是True, 但是若寫成 f1 and f2 == 0 則爲 0,因爲先計算了後面的值(0 and 1)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章