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

 

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