leetcode 235: Lowest Common Ancestor of a Binary Search Tree

本文介绍了一种优化后的二叉树最近公共祖先查找算法,通过提前剪枝减少不必要的递归调用,提高了搜索效率。适用于解决在二叉树中查找两个节点的最近公共祖先的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Use recursion. if none of root, root->left and root->right equal to p or q, return NULL. If left and right are both not NULL, this root is the ancestor. If root equals to p or q, return the root to represent that at least one node is found. If left or right is not NULL, return it to represent at least one node is found in the subtree of this root.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root)
            return NULL;
        TreeNode* left=lowestCommonAncestor(root->left,p,q);
        TreeNode* right=lowestCommonAncestor(root->right,p,q);
        if(left&&right||root==p||root==q)
            return root;
        if(left)
            return left;
        if(right)
            return right;
        return NULL;
    }
};

The code above can be accepted in the Lowest Common Ancestor of a Binary Tree. But it is not the fastest way in this problem. So I add a few conditions to do the pruning. The following is the updated code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root)
            return NULL;
        TreeNode* left,*right;
        if(p->val>root->val&&q->val>root->val)
            left=NULL;
        else
            left=lowestCommonAncestor(root->left,p,q);
        if(p->val<root->val&&q->val<root->val)
            right=NULL;
        else
            right=lowestCommonAncestor(root->right,p,q);
        if(left&&right||root==p||root==q)
            return root;
        if(left)
            return left;
        if(right)
            return right;
        return NULL;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值