Untitled

 avatar
unknown
plain_text
6 months ago
1.4 kB
2
Indexable
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public TreeNode lcaDeepestLeaves(TreeNode root) {
        return findLCA(root).lca;
    }

    private Result findLCA(TreeNode node) {
        if (node == null) return new Result(null, -1);

        // Recur for left and right subtrees
        Result left = findLCA(node.left);
        Result right = findLCA(node.right);

        // Determine the current depth
        int currentDepth = Math.max(left.depth, right.depth) + 1;

        // Determine the LCA based on subtree depths
        if (left.depth == right.depth) {
            return new Result(node, currentDepth);
        } else if (left.depth > right.depth) {
            return new Result(left.lca, currentDepth);
        } else {
            return new Result(right.lca, currentDepth);
        }
    }

    // Helper class to store the LCA and depth
    private static class Result {
        TreeNode lca;
        int depth;

        Result(TreeNode lca, int depth) {
            this.lca = lca;
            this.depth = depth;
        }
    }
}
Editor is loading...
Leave a Comment