Lowest Common Ancestor of the deepest leaves of a Binary Tree | Node of a Binary Tree ; Function to find the depth of the Binary Tree ; If root is not null ; Left recursive subtree ; Right recursive subtree ; Returns the maximum depth ; Function to perform the depth first search on the binary tree ; If root is null ; If curr is equal to depth ; Left recursive subtree ; Right recursive subtree ; If left and right are not null ; Return left , if left is not null Otherwise return right ; Function to find the LCA of the deepest nodes of the binary tree ; If root is null ; Stores the deepest depth of the binary tree ; Return the LCA of the nodes at level depth ; Driver code ; Given Binary Tree
class Node { Node left = null ; Node right = null ; int data ; Node ( int data ) { this . data = data ; } } class GFG { public static int findDepth ( Node root ) { if ( root == null ) return 0 ; int left = findDepth ( root . left ) ; int right = findDepth ( root . right ) ; return 1 + Math . max ( left , right ) ; } public static Node DFS ( Node root , int curr , int depth ) { if ( root == null ) return null ; if ( curr == depth ) return root ; Node left = DFS ( root . left , curr + 1 , depth ) ; Node right = DFS ( root . right , curr + 1 , depth ) ; if ( left != null && right != null ) return root ; return ( left != null ) ? left : right ; } public static Node lcaOfDeepestLeaves ( Node root ) { if ( root == null ) return null ; int depth = findDepth ( root ) - 1 ; return DFS ( root , 0 , depth ) ; } public static void main ( String [ ] args ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; root . right . left = new Node ( 6 ) ; root . right . right = new Node ( 7 ) ; root . right . left . left = new Node ( 8 ) ; root . right . left . right = new Node ( 9 ) ; System . out . println ( lcaOfDeepestLeaves ( root ) . data ) ; } }