@@ -149,28 +149,23 @@ else if (t1 != null && t2 != null) {
149149 public static BTree commonRoot (BTree root , int p , int q ) {
150150 if (root == null )
151151 return null ;
152- if (root .value == p && root .value == q )
152+ if (root .value == p || root .value == q )
153153 return root ;
154154
155155 BTree l = commonRoot (root .left , p , q );
156156 BTree r = commonRoot (root .right , p , q );
157157
158+ /*
158159 if (r != null && r.value != q && r.value != p)
159160 return r;
160161 if (l != null && l.value != q && l.value != p)
161162 return l;
162-
163- if (root .value == p || root .value == q ) {
164- if (l != null || r != null )
165- return root ;
166-
167- } else if (l != null && r != null && l .value != r .value )
163+ */
164+ if (l != null && r != null && l .value != r .value )
168165 return root ;
169166 else
170167 return (l != null ) ? l : r ;
171168
172- return null ;
173-
174169 }
175170
176171 public static BTree coverNode (BTree root , int p ) {
@@ -406,6 +401,8 @@ public static void main(String[] args) {
406401 if (cr != null && coverNode (t1 , p ) != null && coverNode (t1 , q ) != null )
407402 System .out .println (cr .value );
408403
404+ p = 12 ;
405+ q = 13 ;
409406 BTree cr1 = commonRoot (t1 , p , q );
410407 System .out .println ("common root: " + p + " and " + q );
411408 if (cr1 != null && coverNode (t1 , p ) != null && coverNode (t1 , q ) != null )
0 commit comments