【刷算法】LeetCode.236- 二叉树的最近公共祖先

简介: 【刷算法】LeetCode.236- 二叉树的最近公共祖先
示例 1:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
示例 2:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。
说明:
所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉树中。
/**
 * 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(r, a, b) {
  if(r === null || r === a || r === b)
    return r;
  let left = lowestCommonAncestor(r.left, a, b);
  let right = lowestCommonAncestor(r.right, a, b);
  if(left !== null && right !== null) 
    return r;
  return left !== null ? left : right;
};
相关文章
|
4天前
leetcode代码记录(二叉树的所有路径
leetcode代码记录(二叉树的所有路径
12 0
|
4天前
leetcode代码记录(对称二叉树 中序遍历+回文串 为什么不行
leetcode代码记录(对称二叉树 中序遍历+回文串 为什么不行
8 0
|
4天前
leetcode代码记录(二叉树的最小深度
leetcode代码记录(二叉树的最小深度
9 0
|
4天前
leetcode代码记录(二叉树的最大深度
leetcode代码记录(二叉树的最大深度
9 0
|
4天前
leetcode代码记录(翻转二叉树
leetcode代码记录(翻转二叉树
7 0
|
4天前
leetcode代码记录(二叉树的层序遍历
leetcode代码记录(二叉树的层序遍历
12 0
|
4天前
|
算法
leetcode代码记录(二叉树递归遍历
leetcode代码记录(二叉树递归遍历
8 0
|
4天前
|
存储 算法
Leetcode 30天高效刷数据结构和算法 Day1 两数之和 —— 无序数组
给定一个无序整数数组和目标值,找出数组中和为目标值的两个数的下标。要求不重复且可按任意顺序返回。示例:输入nums = [2,7,11,15], target = 9,输出[0,1]。暴力解法时间复杂度O(n²),优化解法利用哈希表实现,时间复杂度O(n)。
22 0
|
4天前
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
[leetcode~dfs]1261. 在受污染的二叉树中查找元素
|
4天前
|
算法
代码随想录算法训练营第六十天 | LeetCode 84. 柱状图中最大的矩形
代码随想录算法训练营第六十天 | LeetCode 84. 柱状图中最大的矩形
23 3