Leetcode236. 二叉树的最近公共祖先

108 阅读1分钟

Offer 驾到,掘友接招!我正在参与2022春招系列活动-刷题打卡任务,点击查看活动详情

一、题目描述:

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 >x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/lo…

二、思路分析:

利用递归判断。三种情况,root为答案,递归root.left或root.right为答案。

空间O(n),时间O(n)

三、AC 代码:

 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function(root, p, q) {
    if(!root) return null;
    if(root===q||root===p) return root;
    let left=lowestCommonAncestor(root.left,p,q);
    let right=lowestCommonAncestor(root.right,p,q);
    if(left&&right) return root;
    return left || right;
};

四、总结:

感觉代码写挺简洁的。递归需要多思考。