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;   
        }
    };
  • 相关阅读:
    React 生命周期及setState原理分析
    React Vue Angular 对比
    盒模型(一)
    CSS尺寸 rem与em原理与区别(二)
    HTTP 状态码
    React渲染机制
    HTTP三次握手四次挥手
    Java常见算法
    SharedPreferences存储数据
    解决ListView滑动上下出现阴影
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6832822.html
Copyright © 2011-2022 走看看