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;   
        }
    };
  • 相关阅读:
    查找->静态查找表->顺序查找(顺序表)
    查找(总结篇)
    树和二叉树->其他(待完善)
    树和二叉树->最优二叉树
    树和二叉树->线索二叉树
    树和二叉树->遍历
    树和二叉树->相互转化
    树和二叉树->存储结构
    树和二叉树->基础知识
    P2921-[USACO08DEC]在农场万圣节Trick or Treat on the Farm
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6832822.html
Copyright © 2011-2022 走看看