• 【Lintcode】088.Lowest Common Ancestor


    题目:

    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.

    Example

    For the following binary tree:

      4
     / 
    3   7
       / 
      5   6
    

    LCA(3, 5) = 4

    LCA(5, 6) = 7

    LCA(6, 7) = 7

    题解:

      左右子树中找到了p和q才返回该root节点,否则返回nullptr

      因为题目中设定两节点一定存在,对于6和7节点,7节点直接返回,不会继续在其左右子树中寻找6,因为此时对于4来说,左子树应该返回nullptr,那么p和q一定在右子树中,只要找到一个节点即可,另一个节点一定在第一个节点的子树中(不是很严谨,因为还有5,6情况,此情况下对于7,左右子树皆不为空,此时7返回的是自身)

    Solution 1 ()

    class Solution {
    public:
        /*bool helper(TreeNode *root,TreeNode *p){
            if(root==nullptr) {
                return false;
            }
            if(root==p) {
                return true;
            }
            
            return helper(root->left,p) || helper(root->right,p);
        } 
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            if(helper(root->left,p) && helper(root->left,q)) {
                return lowestCommonAncestor(root->left,p,q);
            }
            if(helper(root->right,p) && helper(root->right,q)) {
                return lowestCommonAncestor(root->right,p,q);
            }
            
            return root;
        }*/
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            if (root==NULL || root==p || root==q) {
                return root;
            }
            
            TreeNode *left = lowestCommonAncestor(root->left, p, q);
            TreeNode *right = lowestCommonAncestor(root->right, p, q);
            if (left != NULL && right != NULL) {
                return root;
            }
            if (left != NULL) {
                return left;
            }
            if (right != NULL) {
                return right;
            } 
            return NULL;   
        }
    };
  • 相关阅读:
    CHIL-SQL-NULL 函数
    CHIL-SQL-Date 函数
    CHIL-SQL- ALTER TABLE 语句
    CHIL-SQL-AUTO INCREMENT 字段
    CHIL-SQL-VIEW(视图)
    CHIL-SQL-撤销索引、表以及数据库
    CHIL-SQL-CHECK 约束
    CHIL-SQL-DEFAULT 约束
    CHIL-SQL-CREATE INDEX 语句
    CHIL-SQL-FOREIGN KEY 约束
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6832822.html
Copyright © 2020-2023  润新知