首页 > 其他 > 详细

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

时间:2018-08-25 11:11:24      阅读:150      评论:0      收藏:0      [点我收藏+]

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 Search Tree

原文:https://www.cnblogs.com/hankunyan/p/9532704.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!