JAVA solution using DFS, beat 78%


  • 0
    H
        TreeNode lca = null;
        TreeNode p = null;
        TreeNode q = null;
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            this.p = p;
            this.q = q;
            dfs(root);
            return lca;
        }
        
        private boolean dfs(TreeNode n){
            if(n==null) return false;
            boolean left = dfs(n.left);
            boolean right = dfs(n.right);
            if(left&&right){
                lca = n;
            }
            if(left||right){
                if(n==p||n==q){
                    lca = n;
                }
                return true;
            }else if(n==p||n==q){
                return true;
            }
            return false;
        }
    

Log in to reply
 

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