privateTreeNode res =null;publicTreeNodelowestCommonAncestor(TreeNode root,TreeNode p,TreeNode q){dfs(root,p,q);return res;}publicbooleandfs(TreeNode root,TreeNode p,TreeNode q){if(root==null){returnfalse;}boolean left =dfs(root.left,p,q);boolean right =dfs(root.right,p,q);if(left&&right){
res = root;}if(root == p || root ==q){
res = root;}return left || right || root==p || root==q;}