LCA-二叉树公共祖先问题

本文详细介绍了三种不同情况下的二叉树最低公共祖先(LCA)算法实现:二叉搜索树、普通二叉树及带有指向父节点next指针的二叉树。通过具体的LeetCode题目实例,深入解析了每种情况下LCA问题的解决思路和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 二叉搜索树
    leetcode 235. Lowest Common Ancestor of a Binary Search Tree
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root.val>p.val && root.val>q.val){
            return lowestCommonAncestor(root.left,p,q);
        }
        if(root.val<p.val && root.val<q.val){
            return lowestCommonAncestor(root.right,p,q);
        }
        return root;
    }
}
  1. 普通二叉树
    leetcode 236. Lowest Common Ancestor of a Binary Tree
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){
            return right;
        }
        if(right==null){
            return left;
        }
        return root;
    }
}
  1. 带next指针指向父节点的LCA问题
    思路:得到p、q为头节点的两个链表,求链表的公共节点
Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
       TreeNode next; //指向父节点
 *     TreeNode(int x) { val = x; }
 * }
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode p, TreeNode q) {
        TreeNode phead = p;
        TreeNode qhead = q;
        int plength = 0;
        int qlength = 0;
        while(phead.next!=null){
            plength++;
            phead = phead.next;
        }
        while(qhead.next!=null){
            qlength++;
            qhead = qhead.next;
        }
        int len = plength - qlength;
        TreeNode fast = p;
        TreeNode slow = q;
        if(len<0){
            fast = q;
            slow = p;
        }
        for(int i=0; i<len; i++){
            fast = fast.next;
        }
        while(fast.next!=null && slow.next!=null && fast.val!=slow.val){
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值