Oh! My God! My Java Solution beats 99.9%...


  • 0
    Z

    public class Solution {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(helper(p,q)!=null) return p;
        if(helper(q,p)!=null) return q;
        TreeNode tn = helper(root,p);
        return find(tn,q,root);
    }
    
    private TreeNode find(TreeNode root,TreeNode p,TreeNode rt){
        if(helper(root,p)!=null) return root;
        return find(helper(rt,root),p,rt);
    }
    
    private TreeNode helper(TreeNode root,TreeNode p){
        if(root==null||root==p) return root;
        if(root.left==p||root.right==p) return root;*
        TreeNode node = helper(root.left,p);
        if(node==null) node = helper(root.right,p);
        return node;
    }
    

    }


Log in to reply
 

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