leetcode hot 02
1.leetcode hot 01
2.leetcode hot 02
3.leetcode hot 044.leetcode hot 035.leetcode hot 056.leetcode hot 067.leetcode hot 078.leetcode hot 089.leetcode hot 0910.leetcode hot 1011.leetcode hot 1212.leetcode hot 1313.leetcode hot 1414.leetcode hot 1515.leetcode hot 1116.leetcode hot 1617.leetcode hot 1718.leetcode hot 1819.leetcode hot 1920.leetcode hot 2021.leetcode hot 2122.leetcode hot 2223.leetcode hot 2324.leetcode hot 2425.leetcode hot 25解题思路:找祖先从底向上递归后序遍历查找,遇到p,q或者空节点就直接返回对应值,当某个节点的左子树、右子树都返回了值,那么就说明该节点就是最近祖先节点,然后把该节点的值继续往上传,直到根节点返回结果。
/**
* 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 == p || root==q || root==null) return root;
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(left==null && right==null) return null;
if(left==null && right!= null) return right;
if(left!=null && right==null) return left;
else return root;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~