码迷,mamicode.com
首页 > 其他好文 > 详细

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

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

标签:arc   pre   sea   etc   tree   大小   return   comm   递归   

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

标签:arc   pre   sea   etc   tree   大小   return   comm   递归   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!