leetcode:1123. 最深叶节点的最近公共祖先

本文介绍了一种算法,用于解决二叉树中最深叶节点的最近公共祖先问题。通过计算节点左右子树的深度,当左右子树深度相等时,该节点即为所求的最近公共祖先。

链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-deepest-leaves/
每当到达一个节点时,计算其左右子树的深度。若相等则说明其左右子树中均存在最深叶节点,则最近公共祖先即为此节点;若不等则可直接进入较深子树。
java代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int depth = 0;
    public TreeNode lcaDeepestLeaves(TreeNode root) {
        if(root==null)
            return null;
        int leftd = depth(root.left);
        int rightd = depth(root.right);
        if(leftd>rightd)
            return lcaDeepestLeaves(root.left);
        else if(leftd == rightd)
            return root;
        else 
            return lcaDeepestLeaves(root.right);
    }
    private int depth(TreeNode root)
    {
        if(root==null)
            return 0;
        int leftd = depth(root.left);
        int rightd = depth(root.right);
        return Math.max(leftd,rightd)+1;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值