Clean Java AC Solution 13ms with explanation


  • 6
    L
    if(root == null)
    		return null ;
    	TreeNode left = lowestCommonAncestor(root.left, p, q);
    	TreeNode right = lowestCommonAncestor(root.right, p, q);
    		
    	if(root == p || root == q)
    		return root;
    	
    	if(left != null && right == null)
    		return left;
    	else if(left == null && right != null)
    		return right;
    	else if(left == null && right == null)
    		return null;
    	else
    		return root;
    

    Use Post Order Traversal to loop through the tree. Find the left and right child contains tree node p and q and return current node as result.


Log in to reply
 

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