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;   
        }
    };
  • 相关阅读:
    Away3d学习笔记2三维世界的四个基本构件
    实验报告2
    实验报告
    WPF基础——Application
    COM技术内幕(笔记)
    关于一个GetLevelDesc函数 的认知问题
    UI库阶段性进展(完成文字列表,样式列表(样式列表可继承))
    UI库阶段性进展
    UI库阶段性进展(按钮初具雏形)
    UI库阶段性进展(button在文本对齐的基础上增加文本偏移让文本位置更精准)
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6832822.html
Copyright © 2011-2022 走看看