zoukankan      html  css  js  c++  java
  • 【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;   
        }
    };
  • 相关阅读:
    JSP引擎的工作原理
    Hibernate缓存配置
    理解LinkedHashMap
    如何在CMD下运用管理员权限
    sun.misc.BASE64Encoder找不到jar包的解决方法
    访问WEB-INF目录中的JSP文件
    Servlet Filter(过滤器)、Filter是如何实现拦截的、Filter开发入门
    message from server: "Host 'xxx' is not allowed to connect to this MySQL server的解决
    深入Java单例模式
    (八)路径(面包屑导航)分页标签和徽章组件
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6832822.html
Copyright © 2011-2022 走看看