Java solution 17ms


  • 4

    I am using the same function call to check if the subtree contains one of the nodes and to return the result.

    public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode node1, TreeNode node2) {
    
    	if (root == null || root == node1 || root == node2)
    		return root;
    
    	TreeNode leftSearch = lowestCommonAncestor(root.left, node1, node2);
    	TreeNode rightSearch = lowestCommonAncestor(root.right, node1, node2);
    
    	if (leftSearch != null && rightSearch != null) {
    		return root;
    	} else if (leftSearch != null && rightSearch == null) {
    		return leftSearch;
    	} else if (leftSearch == null && rightSearch != null) {
    		return rightSearch;
    	} else {
    		return null;
    	}
    
    }

  • 0
    R

    @IlievskiV Cool Solution!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.