LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Searc

Posted 約束の空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Searc相关的知识,希望对你有一定的参考价值。

236. Lowest Common Ancestor of a Binary Tree

递归寻找p或q,如果找到,层层向上返回,知道 root 左边和右边都不为NULL:if (left!=NULL && right!=NULL) return root;

时间复杂度 O(n),空间复杂度 O(H)

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root==NULL) return NULL;
        if (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;
    }
};

 

235. Lowest Common Ancestor of a Binary Search Tree

实际上比上面那题简单,因为LCA的大小一定是在 p 和 q 中间,只要不断缩小直到在两者之间就行了。

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root->val>p->val && root->val>q->val)
            return lowestCommonAncestor(root->left,p,q);
        if (root->val<p->val && root->val<q->val)
            return lowestCommonAncestor(root->right,p,q);
        return root;
    }
};

 

以上是关于LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Searc的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 236: Lowest Common Ancestor of a Binary Tree

leetcode 236: Lowest Common Ancestor of a Binary Tree

leetcode236 Lowest Common Ancestor of a Binary Tree

leetcode236 - Lowest Common Ancestor of a Binary Tree - medium

LeetCode OJ 236. Lowest Common Ancestor of a Binary Tree

3.2 Lowest Common Ancestor of a Binary Tree(LeetCode 236)