leetcode-1123-DFS

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

给你一个有根节点的二叉树,找到它最深的叶节点的最近公共祖先。

回想一下:

  • 叶节点 是二叉树中没有子节点的节点
  • 树的根节点的 深度 为 0,如果某一节点的深度为 d,那它的子节点的深度就是 d+1
  • 如果我们假定 A 是一组节点 S 的 最近公共祖先,S 中的每个节点都在以 A 为根节点的子树中,且 A 的深度达到此条件下可能的最大值。

示例 1:

输入:root = [1,2,3]
输出:[1,2,3]

示例 2:

输入:root = [1,2,3,4]
输出:[4]

示例 3:

输入:root = [1,2,3,4,5]
输出:[2,4,5]

思路

思路:最深叶子节点的公共祖先的左右子树高度相同,也就是最深叶子节点的深度一定相同。
如果左右子树不等高,高度小的那个子树节点的叶子节点的深度肯定不是最深的(因为比高度大的子树深度小)。
所以,最深叶子节点肯定在深度较大的子树当中,采用深度优先搜索,每次只要继续往深度更大的子树进行递归即可。
如果左右子树深度相同,表示获取到了最深叶子节点的最近公共祖先

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution 
{
    int maxDepth = Integer.MIN_VALUE;
    Queue queue = new LinkedList();
    TreeNode node = null;
    int getDepth(TreeNode root)
    {
        if(root ==null)
            return 0;
        int leftDepth = getDepth(root.left);
        int rightDepth = getDepth(root.right);
        return leftDepth>rightDepth?leftDepth+1:rightDepth+1;

    }
    public TreeNode bianli(TreeNode root,int depth)
    {
        if(root == null)
            return null;
        if(getDepth(root.left) == getDepth(root.right))
        {
            return root;
        }
        else if(getDepth(root.left) > getDepth(root.right))
        {
            return bianli(root.left,depth+1);
        }
        else
            return bianli(root.right,depth+1);
        


    }
    public TreeNode lcaDeepestLeaves(TreeNode root) 
    {
        if(root.left == null && root.right == null)
            return root;
        
        return bianli(root,0);


    }
}

他人解法

class Solution {
    private TreeNode node;
    private int maxDepth;
    public TreeNode lcaDeepestLeaves(TreeNode root) {
        if (root == null) {
            return null;
        }
        dfs(root, 0);
        return node;
    }

    private int dfs(TreeNode root, int depth) {
        if (root == null) {
            return depth;
        }
        depth++;
        int left = dfs(root.left, depth), right = dfs(root.right, depth);
        depth = Math.max(left, right);
        if (left == right && depth >= maxDepth) {
            node = root;
            maxDepth = depth;
        }
        return depth;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值