Leetcode 第236題:Lowest Common Ancestor of a Binary Tree--二叉樹的最近公共祖先(C++、Python)

題目地址:Lowest Common Ancestor of a Binary Tree


題目簡介:

給定一個二叉樹, 找到該樹中兩個指定節點的最近公共祖先。

百度百科中最近公共祖先的定義爲:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示爲一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度儘可能大(一個節點也可以是它自己的祖先)。”

例如,給定如下二叉樹: root = [3,5,1,6,2,0,8,null,null,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 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.

假設所有的點都是獨一無二的,p,q相異並肯定存在。


題目解析:

二叉樹的遍歷問題大部分考慮遞歸。根據上面的兩個例子,第一個例子是都在目標結果點的左右節點,用於遞歸的時候,只能發現其中一支和一個結果,於是此時需要返回根節點。(代表了在兩個子樹的情況)

第二個例子是一個節點是另外一個節點的頂點,只需要確定右子樹沒有兩個節點的頂點,於是只要在右子樹裏碰到某個頂點便是結果。(代表了在同一個子樹的情況)

遞歸的情況,將上述兩種情況都考慮即可。

C++版:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (!root || root == p || root == q) 
            return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if (!left && !right)
            return NULL;
        if (left && right)
            return root;
        return left ? left : right;
    }
};

Python版:

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> '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 not left and not right:
            return None
        if left and right:
            return root
        return left if left else right

 

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