

Leetcode 236 二叉树的最近公共祖先(Lowest Common Ancestor of a Binary Tree) 题解...
source link: https://nicksxs.me/2021/05/23/Leetcode-236-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88-Lowest-Common-Ancestor-of-a-Binary-Tree-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Leetcode 236 二叉树的最近公共祖先(Lowest Common Ancestor of a Binary Tree) 题解分析
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p
and q
as the lowest node in T
that has both p
and q
as descendants (where we allow a node to be a descendant of itself).”
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T
的两个节点 p
、q
,最近公共祖先表示为一个节点 x
,满足 x
是 p
、q
的祖先且 x
的深度尽可能大(一个节点也可以是它自己的祖先)。”
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// 如果当前节点就是 p 或者是 q 的时候,就直接返回了
// 当没找到,即 root == null 的时候也会返回 null,这是个重要的点
if (root == null || root == p || root == q) return root;
// 在左子树中找 p 和 q
TreeNode left = lowestCommonAncestor(root.left, p, q);
// 在右子树中找 p 和 q
TreeNode right = lowestCommonAncestor(root.right, p, q);
// 当左边是 null 就直接返回右子树,但是这里不表示右边不是 null,所以这个顺序是不影响的
// 考虑一种情况,如果一个节点的左右子树都是 null,那么其实对于这个节点来说首先两个子树分别调用
// lowestCommonAncestor会在开头就返回 null,那么就是上面 left 跟 right 都是 null,然后走下面的判断的时候
// 其实第一个 if 就返回了 null,如此递归返回就能达到当子树中没有找到 p 或者 q 的时候只返回 null
if (left == null) {
return right;
} else if (right == null) {
return left;
} else {
return root;
}
// if (right == null) {
// return left;
// } else if (left == null) {
// return right;
// } else {
// return root;
// }
// return left == null ? right : right == null ? left : root;
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK