public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B) {
      if (root == null) 
      return null;
      if (check(root, A)&&check(root,B)){
          return lowestCommonAncestor(root,A,B);
      }
      else {
          return null;
      }
    }    

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
        if (root == null || root == A || root == B) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, A, B);
        TreeNode right = lowestCommonAncestor(root.right, A, B);

        if (left != null && right != null) {
            return root;
        }
        return left == null ? right : left;
    }
   //check if node in the tree 
    public boolean check(TreeNode root, TreeNode node){

      if (root.left != null && check(root.left, node)) {
         return true;
      }
      if (root.right != null && check(root.right, node)){
       return true;
      }
      if (root == node) {
          return true;
      } 
       return false;
    }

results matching ""

    No results matching ""