0
点赞
收藏
分享

微信扫一扫

【每日一题】【二叉树】【递归】236. 二叉树的最近公共祖先-211126/220114/220203

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

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

【每日一题】【二叉树】【递归】236. 二叉树的最近公共祖先-211126/220114/220203_商业

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left == null && right == null) { //均为空时,说明都到达叶子结点,即没有找到
return null;
} else if(left != null && right != null) { //均为非空时,说明左右均找到了p或q,则返回根节点
return root;
} else { //否则,有一边没找到,则返回另一边
return left == null ? right : left;
}
}
}

 


本文来自博客园,作者:​​哥们要飞​​​,转载请注明原文链接:​​javascript:void(0)p/15609710.html​​


举报

相关推荐

0 条评论