236 二叉树的最近公共祖先

  1. 递归终止条件

    • 当前节点为空,返回null
    • 当前节点是pq中的一个,直接返回当前节点,因为该节点可能是LCA。
  2. 递归左右子树

    • 分别递归左子树和右子树,获取左右子树的处理结果leftright
  3. 处理递归结果

    • 左右子树均非空:说明当前节点是pq的LCA,返回当前节点。
    • 左子树结果为空:说明LCA在右子树中,返回右子树结果right
    • 右子树结果为空:说明LCA在左子树中,返回左子树结果left

/**
 * 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 || root == p || root == q) return root;

        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);

        if (left && right) return root;
        if (left) return left;
        if (right) return right;
        return nullptr;
    }
};
  1. 时间复杂度 O(n):每个节点最多被访问一次
  2. 空间复杂度 O(h):递归栈深度与树高度成正比
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值