leetcode1123. 最深叶节点的最近公共祖先(dfs)

283 阅读1分钟

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

回想一下:

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

示例 1:

输入:root = [1,2,3]
输出:[1,2,3]
解释:
最深的叶子是值为 2 和 3 的节点。
这些叶子的最近共同祖先是值为 1 的节点。
返回的答案为序列化的 TreeNode 对象(不是数组)"[1,2,3]" 。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
       int maxLen=Integer.MIN_VALUE;
    TreeNode maxRoot;
    public TreeNode lcaDeepestLeaves(TreeNode root) {

         po(root,0);
         return maxRoot;
    }
    public int  po(TreeNode root,int level) {

        if(root==null) return level;//返回深度

        int l=po(root.left,level+1);
        int r=po(root.right,level+1);
        if(l==r&&l>=maxLen) {//如果左右子树都存在相等的最深叶子节点
            maxLen=l;
            maxRoot=root;
        }
        return Math.max(l,r);//返回最深叶子节点的高度
    }
}