My java solution


  • 0
    L
    public class Solution {
    TreeNode k=null;
    boolean y1=false,y2=false;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null) return  null;
        find(root,p,q);
        return k;
    }
    public void find(TreeNode root,TreeNode p, TreeNode q){
        if(root==null) return ;
        if(root==p&&root==q) {k=root;return;}
        if(root==p || root==q) {
            if(y1) {y2=true;return;}
            y1=true;
            if(q==root){
                q=p;
                p=root;
            }
            if(p.left!=null) find(p.left,p,q);
            if(p.right!=null) find(p.right,p,q);
            if(y1 && y2) {k=p;y1=false;y2=false;return;}
        }
        if(y1){
            if(root.left!=null) {find(root.left,p,q);}
            if(root.right!=null) {find(root.right,p,q);}
            if(y1&&y2) {return;} 
        }else{
            if(root.left!=null) {find(root.left,p,q);}
            if(root.right!=null) {find(root.right,p,q);}
            if(y1&&y2) {k=root;y1=false;y2=false;}
        }
    }
    

    }


Log in to reply
 

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