My 10ms Java code beats 99.89%

  • 0
    public class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if(root==null) return null;
            TreeNode res = root;
            if(ancestor(p,q)) return p;
            if(ancestor(q,p)) return q;
            return helper(root,p,q,res);
        boolean ancestor(TreeNode root, TreeNode tmp){
            if(root==null) return false;
            if(root == tmp) return true;
            return ancestor(root.left,tmp) || ancestor(root.right,tmp);
        TreeNode helper(TreeNode root,TreeNode p,TreeNode q,TreeNode res){
                if(root.left!=null) res = helper(root.left,p,q,res);
                if(root.right!=null) res = helper(root.right,p,q,res);
            return res;

Log in to reply

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