力扣865

python:

class Solution:
    def subtreeWithAllDeepest(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        def depth(node):
            if node is None:
                return 0
            return max(depth(node.left),depth(node.right))+1

        left = depth(root.left)
        right = depth(root.right)

        if left == right:
            return root

        if left>right:
            return self.subtreeWithAllDeepest(root.left)
        else:
            return self.subtreeWithAllDeepest(root.right)

Java:

class Solution {
    public TreeNode subtreeWithAllDeepest(TreeNode root) {
        int left = depth(root.left);
        int right = depth(root.right);
        if(left == right){
            return root;
        }
        return subtreeWithAllDeepest(left>right?root.left:root.right);
    }
    private int depth(TreeNode node) {
        if(node == null){
            return 0;
        }
        return Math.max(depth(node.left),depth(node.right))+1;
    }
}