树中两个节点的最低公共祖先

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:54   1536   0

题目描述

Leetcode : 235. Lowest Common Ancestor of a Binary Search Tree

Leetcode : 236. Lowest Common Ancestor of a Binary Tree

解题思路

AC代码

//leetcode 235
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == nullptr)
            return root;
        if(root->val > p->val && root->val > q->val)
            return lowestCommonAncestor(root->left, p, q);
        else if(root->val<p->val && root->val<q->val)
            return lowestCommonAncestor(root->right, p, q);
        else
             return root;
    }
};
//leetcode 236
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==nullptr)
            return root;
        if(root->val == p->val || root->val == q->val)
            return root;
        TreeNode* leftNode = lowestCommonAncestor(root->left, p, q);
        TreeNode* rightNode = lowestCommonAncestor(root->right, p, q);
        if(leftNode && rightNode)
            return root;
        return leftNode?leftNode:rightNode?rightNode:nullptr;
    }
};

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP