> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/01-08-2022-236.md).

# 01/08/2022 236

1. class Solution{&#x20;
2. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

   ```
       //divide and conquer
       
       if(root == null || root == p || root == q) return root;
       
       TreeNode left = lowestCommonAncestor(root.left, p, q);
       TreeNode right = lowestCommonAncestor(root.right, p, q);
       
       if (left != null && right != null){
           return root;
       } else if(left != null){
           return left;
       }else if (right != null){
           return right;
       }
       
       return null;
   }
   ```

   }

use divide and conquer to get the result left and right. If left and right both are not null, then LCA will be root. If left is not null and right is null, then return left. if right is not null and left is null, then return left.&#x20;

T O(n)  Space O(n) worst case
